Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,222 +1,194 @@
|
|
1 |
import gradio as gr
|
2 |
-
from PIL import Image
|
3 |
-
import numpy as np
|
4 |
import cv2
|
|
|
|
|
|
|
|
|
5 |
import torch
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
def __init__(self):
|
14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
-
#
|
|
|
17 |
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
|
|
22 |
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
gray = image
|
27 |
-
|
28 |
-
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(16,16))
|
29 |
-
enhanced = clahe.apply(gray)
|
30 |
-
enhanced = cv2.fastNlMeansDenoising(enhanced, None, h=10, templateWindowSize=7, searchWindowSize=21)
|
31 |
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
if texture_complexity > 100:
|
51 |
-
return "Textura muito complexa e detalhada", texture_complexity
|
52 |
-
elif texture_complexity > 50:
|
53 |
-
return "Textura moderadamente complexa", texture_complexity
|
54 |
-
else:
|
55 |
-
return "Textura simples ou uniforme", texture_complexity
|
56 |
-
|
57 |
-
def _analyze_color(self, image, enhanced):
|
58 |
-
"""Análise de cor."""
|
59 |
-
if len(image.shape) == 3:
|
60 |
-
hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
|
61 |
-
lab = cv2.cvtColor(image, cv2.COLOR_RGB2LAB)
|
62 |
-
|
63 |
-
hue_entropy = entropy(hsv[:,:,0].flatten())
|
64 |
-
sat_entropy = entropy(hsv[:,:,1].flatten())
|
65 |
-
light_entropy = entropy(lab[:,:,0].flatten())
|
66 |
-
|
67 |
-
color_complexity = (hue_entropy * sat_entropy * light_entropy) ** (1/3)
|
68 |
-
|
69 |
-
if color_complexity > 4:
|
70 |
-
return "Coloração muito rica e complexa", color_complexity
|
71 |
-
elif color_complexity > 2:
|
72 |
-
return "Coloração moderadamente complexa", color_complexity
|
73 |
-
else:
|
74 |
-
return "Coloração simples ou uniforme", color_complexity
|
75 |
-
return "Não foi possível analisar coloração", 0
|
76 |
-
|
77 |
-
def _analyze_spots(self, image, enhanced):
|
78 |
-
"""Análise de manchas."""
|
79 |
-
spots = []
|
80 |
-
for scale in [0.5, 1.0, 2.0]:
|
81 |
-
scaled = cv2.resize(enhanced, None, fx=scale, fy=scale)
|
82 |
|
83 |
-
|
84 |
-
|
85 |
-
|
|
|
86 |
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
spots.extend(valid_spots)
|
91 |
|
92 |
-
if
|
93 |
-
return
|
94 |
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
101 |
else:
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
return f"Anéis altamente concêntricos ({len(circles)} detectados)", 1/concentricity
|
121 |
-
elif concentricity < 0.2:
|
122 |
-
return f"Anéis moderadamente concêntricos ({len(circles)} detectados)", 1/concentricity
|
123 |
else:
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
"
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
134 |
|
135 |
-
|
136 |
-
|
137 |
|
138 |
-
|
139 |
-
|
140 |
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
"
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
# [Previous comprehensive_analysis method remains the same...]
|
188 |
-
|
189 |
-
def create_gradio_interface():
|
190 |
-
analyzer = IridologyAnalyzer()
|
191 |
-
|
192 |
-
def process_image(image):
|
193 |
-
if image is None:
|
194 |
-
return "Por favor, faça o upload de uma imagem."
|
195 |
-
return analyzer.comprehensive_analysis(image)
|
196 |
-
|
197 |
-
iface = gr.Interface(
|
198 |
-
fn=process_image,
|
199 |
-
inputs=gr.Image(type="numpy", label="Upload da Imagem do Olho"),
|
200 |
-
outputs=gr.Textbox(label="Resultados da Análise Avançada", lines=30),
|
201 |
-
title="Analisador de Iridologia Avançado com IA",
|
202 |
-
description="""
|
203 |
-
Sistema avançado de análise de íris usando técnicas de processamento de imagem e correlações de saúde.
|
204 |
-
Faça o upload de uma imagem clara do olho para análise detalhada.
|
205 |
-
|
206 |
-
IMPORTANTE: Esta ferramenta é apenas para fins educativos e NÃO substitui diagnóstico médico profissional.
|
207 |
-
|
208 |
-
Recomendações para resultados otimizados:
|
209 |
-
1. Use imagens bem iluminadas e de alta resolução
|
210 |
-
2. Garanta que a íris esteja em foco perfeito
|
211 |
-
3. Evite reflexos e sombras
|
212 |
-
4. Enquadre apenas o olho na imagem, centralizando a íris
|
213 |
-
""",
|
214 |
-
examples=[],
|
215 |
-
cache_examples=True
|
216 |
-
)
|
217 |
-
|
218 |
-
return iface
|
219 |
|
220 |
if __name__ == "__main__":
|
221 |
-
iface = create_gradio_interface()
|
222 |
iface.launch()
|
|
|
1 |
import gradio as gr
|
|
|
|
|
2 |
import cv2
|
3 |
+
import numpy as np
|
4 |
+
from PIL import Image
|
5 |
+
from dataclasses import dataclass
|
6 |
+
from typing import Tuple, Dict, List
|
7 |
import torch
|
8 |
+
import torch.nn.functional as F
|
9 |
+
import torchvision.transforms as transforms
|
10 |
+
|
11 |
+
@dataclass
|
12 |
+
class IrisZone:
|
13 |
+
name: str
|
14 |
+
inner_ratio: float
|
15 |
+
outer_ratio: float
|
16 |
+
color: Tuple[int, int, int]
|
17 |
+
angle_start: float = 0
|
18 |
+
angle_end: float = 360
|
19 |
+
|
20 |
+
class IrisAnalyzer:
|
21 |
def __init__(self):
|
22 |
+
# Define zonas com cores distintas e ângulos específicos
|
23 |
+
self.zones = [
|
24 |
+
IrisZone("Zona Cerebral/Neural", 0.85, 1.0, (255, 0, 0)),
|
25 |
+
IrisZone("Zona Digestiva", 0.7, 0.85, (0, 255, 0)),
|
26 |
+
IrisZone("Zona Respiratória", 0.55, 0.7, (0, 0, 255)),
|
27 |
+
IrisZone("Zona Circulatória", 0.4, 0.55, (255, 255, 0)),
|
28 |
+
IrisZone("Zona Linfática", 0.25, 0.4, (255, 0, 255)),
|
29 |
+
IrisZone("Zona Endócrina", 0.15, 0.25, (0, 255, 255)),
|
30 |
+
IrisZone("Zona Pupilar", 0, 0.15, (128, 128, 128))
|
31 |
+
]
|
32 |
+
|
33 |
+
def preprocess_image(self, img: np.ndarray) -> np.ndarray:
|
34 |
+
"""Pré-processa a imagem para melhorar a detecção"""
|
35 |
+
# Converter para escala de cinza
|
36 |
+
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
37 |
+
|
38 |
+
# Aplicar equalização de histograma adaptativo
|
39 |
+
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
|
40 |
+
enhanced = clahe.apply(gray)
|
41 |
|
42 |
+
# Redução de ruído
|
43 |
+
denoised = cv2.fastNlMeansDenoising(enhanced)
|
44 |
|
45 |
+
return denoised
|
46 |
+
|
47 |
+
def detect_pupil(self, img: np.ndarray) -> Tuple[int, int, int]:
|
48 |
+
"""Detecta a pupila usando técnicas avançadas"""
|
49 |
+
preprocessed = self.preprocess_image(img)
|
50 |
|
51 |
+
# Threshold adaptativo
|
52 |
+
_, thresh = cv2.threshold(preprocessed, 30, 255,
|
53 |
+
cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
|
|
|
|
|
|
|
|
|
|
|
54 |
|
55 |
+
# Operações morfológicas
|
56 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
|
57 |
+
morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
|
58 |
+
|
59 |
+
# Encontrar contornos
|
60 |
+
contours, _ = cv2.findContours(morph, cv2.RETR_EXTERNAL,
|
61 |
+
cv2.CHAIN_APPROX_SIMPLE)
|
62 |
+
|
63 |
+
if not contours:
|
64 |
+
return None
|
65 |
+
|
66 |
+
# Encontrar o contorno mais circular
|
67 |
+
max_circularity = 0
|
68 |
+
best_contour = None
|
69 |
+
|
70 |
+
for contour in contours:
|
71 |
+
area = cv2.contourArea(contour)
|
72 |
+
perimeter = cv2.arcLength(contour, True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
|
74 |
+
if perimeter == 0:
|
75 |
+
continue
|
76 |
+
|
77 |
+
circularity = 4 * np.pi * area / (perimeter * perimeter)
|
78 |
|
79 |
+
if circularity > max_circularity:
|
80 |
+
max_circularity = circularity
|
81 |
+
best_contour = contour
|
|
|
82 |
|
83 |
+
if best_contour is None:
|
84 |
+
return None
|
85 |
|
86 |
+
# Ajustar círculo
|
87 |
+
(x, y), radius = cv2.minEnclosingCircle(best_contour)
|
88 |
+
return (int(x), int(y), int(radius))
|
89 |
+
|
90 |
+
def analyze_zone(self, img: np.ndarray, mask: np.ndarray) -> Dict:
|
91 |
+
"""Analisa características da zona usando a máscara"""
|
92 |
+
# Extrair características da região
|
93 |
+
mean_color = cv2.mean(img, mask=mask)
|
94 |
+
|
95 |
+
# Calcular textura usando GLCM
|
96 |
+
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
97 |
+
zone_pixels = cv2.bitwise_and(gray, gray, mask=mask)
|
98 |
+
|
99 |
+
# Análise de textura básica
|
100 |
+
if np.sum(mask) > 0:
|
101 |
+
std_dev = np.std(zone_pixels[mask > 0])
|
102 |
+
mean_intensity = np.mean(zone_pixels[mask > 0])
|
103 |
else:
|
104 |
+
std_dev = 0
|
105 |
+
mean_intensity = 0
|
106 |
+
|
107 |
+
return {
|
108 |
+
'mean_intensity': mean_intensity,
|
109 |
+
'std_dev': std_dev,
|
110 |
+
'color_variation': mean_color[:3]
|
111 |
+
}
|
112 |
+
|
113 |
+
def interpret_zone(self, analysis: Dict) -> str:
|
114 |
+
"""Interpreta os resultados da análise"""
|
115 |
+
intensity = analysis['mean_intensity']
|
116 |
+
variation = analysis['std_dev']
|
117 |
+
|
118 |
+
if intensity < 85:
|
119 |
+
base_condition = "Possível área de atenção"
|
120 |
+
elif intensity < 170:
|
121 |
+
base_condition = "Área moderada"
|
|
|
|
|
|
|
122 |
else:
|
123 |
+
base_condition = "Área normal"
|
124 |
+
|
125 |
+
detail = f"(Intensidade: {intensity:.1f}, Variação: {variation:.1f})"
|
126 |
+
return f"{base_condition} {detail}"
|
127 |
+
|
128 |
+
def analyze_iris(self, img: np.ndarray) -> Tuple[np.ndarray, Dict]:
|
129 |
+
"""Análise principal da íris"""
|
130 |
+
# Criar cópia para desenho
|
131 |
+
output_img = img.copy()
|
132 |
+
results = {}
|
133 |
+
|
134 |
+
# Detectar pupila
|
135 |
+
pupil = self.detect_pupil(img)
|
136 |
+
if pupil is None:
|
137 |
+
return img, {"Erro": "Não foi possível detectar a pupila"}
|
138 |
+
|
139 |
+
x, y, pupil_radius = pupil
|
140 |
|
141 |
+
# Estimar raio da íris (aproximadamente 4x o raio da pupila)
|
142 |
+
iris_radius = pupil_radius * 4
|
143 |
|
144 |
+
# Desenhar círculo da pupila
|
145 |
+
cv2.circle(output_img, (x, y), pupil_radius, (0, 0, 0), 2)
|
146 |
|
147 |
+
# Analisar cada zona
|
148 |
+
for zone in self.zones:
|
149 |
+
inner_r = int(iris_radius * zone.inner_ratio)
|
150 |
+
outer_r = int(iris_radius * zone.outer_ratio)
|
151 |
+
|
152 |
+
# Criar máscara para a zona
|
153 |
+
mask = np.zeros(img.shape[:2], dtype=np.uint8)
|
154 |
+
cv2.circle(mask, (x, y), outer_r, 255, -1)
|
155 |
+
cv2.circle(mask, (x, y), inner_r, 0, -1)
|
156 |
+
|
157 |
+
# Desenhar círculos da zona
|
158 |
+
cv2.circle(output_img, (x, y), outer_r, zone.color, 2)
|
159 |
+
|
160 |
+
# Analisar zona
|
161 |
+
analysis = self.analyze_zone(img, mask)
|
162 |
+
interpretation = self.interpret_zone(analysis)
|
163 |
+
results[zone.name] = interpretation
|
164 |
+
|
165 |
+
# Adicionar texto
|
166 |
+
text_x = x - iris_radius
|
167 |
+
text_y = y + outer_r
|
168 |
+
cv2.putText(output_img, zone.name, (text_x, text_y),
|
169 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.5, zone.color, 1)
|
170 |
+
|
171 |
+
return output_img, results
|
172 |
+
|
173 |
+
def process_image(img):
|
174 |
+
analyzer = IrisAnalyzer()
|
175 |
+
return analyzer.analyze_iris(np.array(img))
|
176 |
+
|
177 |
+
# Interface Gradio
|
178 |
+
iface = gr.Interface(
|
179 |
+
fn=process_image,
|
180 |
+
inputs=gr.Image(),
|
181 |
+
outputs=[
|
182 |
+
gr.Image(label="Análise Visual"),
|
183 |
+
gr.JSON(label="Resultados da Análise por Zona")
|
184 |
+
],
|
185 |
+
title="Analisador Avançado de Íris (Baseado na Teoria de Jensen)",
|
186 |
+
description="""AVISO: Esta é uma demonstração educacional baseada na teoria de iridologia.
|
187 |
+
Esta não é uma ferramenta diagnóstica validada cientificamente e não deve ser usada para
|
188 |
+
decisões médicas. Consulte sempre um profissional de saúde qualificado para diagnósticos.""",
|
189 |
+
examples=[],
|
190 |
+
theme="default"
|
191 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
192 |
|
193 |
if __name__ == "__main__":
|
|
|
194 |
iface.launch()
|