HavajOrtho commited on
Commit
a1d71e6
·
verified ·
1 Parent(s): c82584b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -0
app.py CHANGED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ from PIL import Image
4
+ import matplotlib.pyplot as plt
5
+ import io
6
+ from pyceph.pyceph import predict
7
+
8
+ def process_image(image):
9
+ """
10
+ Обрабатывает изображение и возвращает результат с отмеченными точками
11
+ """
12
+ if image is None:
13
+ return None, "Пожалуйста, загрузите изображение"
14
+
15
+ # Сохраняем временное изображение
16
+ temp_path = "temp_input.jpg"
17
+ image.save(temp_path)
18
+
19
+ # Получаем предсказания
20
+ try:
21
+ results = predict(image_src=temp_path, device='cpu')
22
+
23
+ # Создаем изображение с точками
24
+ fig, ax = plt.subplots(figsize=(10, 10))
25
+ ax.imshow(image)
26
+
27
+ # Рисуем точки и подписи
28
+ landmarks_text = []
29
+ for landmark_dict in results:
30
+ for name, (x, y) in landmark_dict.items():
31
+ ax.plot(x, y, 'ro', markersize=8)
32
+ ax.text(x, y, name, fontsize=8, color='yellow',
33
+ bbox=dict(boxstyle='round,pad=0.3', facecolor='black', alpha=0.5))
34
+ landmarks_text.append(f"{name}: ({x}, {y})")
35
+
36
+ ax.axis('off')
37
+ plt.tight_layout()
38
+
39
+ # Конвертируем в изображение
40
+ buf = io.BytesIO()
41
+ plt.savefig(buf, format='png', bbox_inches='tight', dpi=150)
42
+ buf.seek(0)
43
+ result_image = Image.open(buf)
44
+ plt.close()
45
+
46
+ # Форматируем текст с координатами
47
+ landmarks_output = "\n".join(landmarks_text)
48
+
49
+ return result_image, landmarks_output
50
+
51
+ except Exception as e:
52
+ return None, f"Ошибка обработки: {str(e)}"
53
+
54
+ # Создаем интерфейс Gradio
55
+ with gr.Blocks(title="Py-Ceph: Цефалометрический анализ") as demo:
56
+ gr.Markdown("""
57
+ # 🦷 Py-Ceph: Определение цефалометрических точек
58
+
59
+ Загрузите боковой рентгеновский снимок черепа (цефалограмму),
60
+ и модель автоматически определит 19 анатомических точек.
61
+
62
+ Основано на [py-ceph](https://github.com/zhangted/py-ceph)
63
+ """)
64
+
65
+ with gr.Row():
66
+ with gr.Column():
67
+ input_image = gr.Image(type="pil", label="Загрузите цефалограмму")
68
+ submit_btn = gr.Button("Анализировать", variant="primary")
69
+
70
+ with gr.Column():
71
+ output_image = gr.Image(label="Результат с точками")
72
+ output_text = gr.Textbox(label="Координаты точек", lines=20)
73
+
74
+ submit_btn.click(
75
+ fn=process_image,
76
+ inputs=input_image,
77
+ outputs=[output_image, output_text]
78
+ )
79
+
80
+ gr.Markdown("""
81
+ ### Определяемые точки:
82
+ Sella, Nasion, Orbitale, Porion, Subspinale, Supramentale, Pogonion,
83
+ Menton, Gnathion, Gonion, Incision Inferius, Incision Superius,
84
+ Upper Lip, Lower Lip, Subnasale, Soft Tissue Pogonion,
85
+ Posterior Nasal Spine, Anterior Nasal Spine, Articulare
86
+ """)
87
+
88
+ if __name__ == "__main__":
89
+ demo.launch()