Update app.py
Browse files
app.py
CHANGED
@@ -3,9 +3,9 @@ import numpy as np
|
|
3 |
import matplotlib.pyplot as plt
|
4 |
from ultralytics import YOLO
|
5 |
import gradio as gr
|
6 |
-
from matplotlib.patches import
|
7 |
|
8 |
-
# Cargar el modelo YOLO
|
9 |
model = YOLO("model.pt")
|
10 |
|
11 |
def process_image(image):
|
@@ -22,17 +22,19 @@ def process_image(image):
|
|
22 |
# Crear una imagen en blanco para las máscaras
|
23 |
mask_image = np.zeros_like(img, dtype=np.uint8)
|
24 |
|
|
|
|
|
|
|
25 |
# Procesar resultados
|
26 |
for result in results:
|
27 |
-
# Verificar si se detectaron máscaras
|
28 |
if result.masks is not None and len(result.masks.data) > 0:
|
29 |
-
# Obtener
|
30 |
-
masks = result.masks.data.cpu().numpy()
|
31 |
-
confidences = result.boxes.conf.cpu().numpy()
|
32 |
classes = result.boxes.cls.cpu().numpy().astype(int)
|
33 |
-
names = model.names
|
34 |
|
35 |
-
# Normalizar
|
36 |
confidences_norm = (confidences - confidences.min()) / (confidences.max() - confidences.min() + 1e-6)
|
37 |
|
38 |
# Redimensionar las máscaras para que coincidan con el tamaño de la imagen
|
@@ -40,46 +42,39 @@ def process_image(image):
|
|
40 |
for mask in masks:
|
41 |
mask_resized = cv2.resize(mask, (img.shape[1], img.shape[0]), interpolation=cv2.INTER_LINEAR)
|
42 |
resized_masks.append(mask_resized)
|
43 |
-
resized_masks = np.array(resized_masks)
|
44 |
|
45 |
# Aplicar suavizado a las máscaras
|
46 |
smoothed_masks = []
|
47 |
for mask in resized_masks:
|
48 |
-
# Convertir la máscara a escala de grises (valores entre 0 y 255)
|
49 |
mask_uint8 = (mask * 255).astype(np.uint8)
|
50 |
-
|
51 |
-
blurred_mask = cv2.GaussianBlur(mask_uint8, (7, 7), 0)
|
52 |
-
# Normalizar y convertir de nuevo a rango [0, 1]
|
53 |
mask_smoothed = blurred_mask.astype(np.float32) / 255.0
|
54 |
smoothed_masks.append(mask_smoothed)
|
55 |
smoothed_masks = np.array(smoothed_masks)
|
56 |
|
57 |
-
# Ordenar
|
58 |
sorted_indices = np.argsort(-confidences)
|
59 |
sorted_masks = smoothed_masks[sorted_indices]
|
60 |
sorted_confidences = confidences[sorted_indices]
|
61 |
sorted_confidences_norm = confidences_norm[sorted_indices]
|
62 |
sorted_classes = classes[sorted_indices]
|
63 |
|
64 |
-
# Definir
|
65 |
colormap = plt.cm.get_cmap('viridis')
|
66 |
|
67 |
-
#
|
68 |
-
mask_indices = np.full((img.shape[0], img.shape[1]), -1, dtype=int)
|
69 |
-
|
70 |
-
# Procesar cada máscara y asignar máscaras de mayor probabilidad a los píxeles
|
71 |
for idx_in_order, (idx, mask, conf_norm, conf, cls) in enumerate(zip(sorted_indices, sorted_masks, sorted_confidences_norm, sorted_confidences, sorted_classes)):
|
72 |
-
mask_bool = mask > 0.5
|
73 |
-
#
|
74 |
-
|
75 |
if not np.any(update_mask):
|
76 |
-
continue
|
77 |
-
mask_indices[update_mask] = idx
|
78 |
|
79 |
-
# Obtener
|
80 |
color_rgb = colormap(conf_norm)[:3]
|
81 |
-
color_rgb = [int(c *
|
82 |
-
color_bgr = color_rgb[::-1] # Convertir de RGB a BGR
|
83 |
|
84 |
# Almacenar la información de la máscara
|
85 |
mask_info = {
|
@@ -93,43 +88,36 @@ def process_image(image):
|
|
93 |
|
94 |
# Asignar colores a los píxeles correspondientes en la imagen de máscaras
|
95 |
for i in range(3):
|
96 |
-
mask_image[:, :, i][update_mask] = color_bgr[i]
|
97 |
|
98 |
-
# Superponer la imagen de máscaras sobre la imagen original
|
99 |
-
alpha = 0.2 # Transparencia ajustada
|
100 |
img_with_masks = cv2.addWeighted(img.astype(np.float32), 1, mask_image.astype(np.float32), alpha, 0).astype(np.uint8)
|
101 |
|
102 |
else:
|
103 |
-
# Si no hay máscaras, usar la imagen original
|
104 |
img_with_masks = img.copy()
|
105 |
-
print("No se detectaron máscaras en esta imagen.")
|
106 |
|
107 |
-
# Convertir
|
108 |
-
img_rgb = cv2.cvtColor(
|
109 |
-
img_with_masks_rgb = cv2.cvtColor(img_with_masks, cv2.COLOR_BGR2RGB)
|
110 |
|
111 |
-
# Crear una figura
|
112 |
fig, ax = plt.subplots(figsize=(8, 8))
|
113 |
-
ax.imshow(
|
114 |
ax.axis('off')
|
115 |
|
116 |
# Crear la leyenda si hay máscaras detectadas
|
117 |
if mask_info_list:
|
118 |
-
from matplotlib.patches import Patch
|
119 |
handles = []
|
120 |
labels = []
|
121 |
for mask_info in mask_info_list:
|
122 |
-
color_rgb = mask_info['color_rgb']
|
123 |
-
|
124 |
-
patch = Patch(facecolor=color_normalized)
|
125 |
label = f"{mask_info['class']}: {mask_info['confidence']:.2f}"
|
126 |
handles.append(patch)
|
127 |
labels.append(label)
|
128 |
|
129 |
-
# Añadir la leyenda al gráfico
|
130 |
ax.legend(handles, labels, loc='upper right')
|
131 |
|
132 |
-
# Convertir la figura
|
133 |
fig.canvas.draw()
|
134 |
img_figure = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
|
135 |
img_figure = img_figure.reshape(fig.canvas.get_width_height()[::-1] + (3,))
|
|
|
3 |
import matplotlib.pyplot as plt
|
4 |
from ultralytics import YOLO
|
5 |
import gradio as gr
|
6 |
+
from matplotlib.patches import Patch
|
7 |
|
8 |
+
# Cargar el modelo YOLO
|
9 |
model = YOLO("model.pt")
|
10 |
|
11 |
def process_image(image):
|
|
|
22 |
# Crear una imagen en blanco para las máscaras
|
23 |
mask_image = np.zeros_like(img, dtype=np.uint8)
|
24 |
|
25 |
+
# Transparencia ajustada para la superposición de máscaras
|
26 |
+
alpha = 0.4 # Un valor más bajo aumenta la transparencia y reduce la saturación
|
27 |
+
|
28 |
# Procesar resultados
|
29 |
for result in results:
|
|
|
30 |
if result.masks is not None and len(result.masks.data) > 0:
|
31 |
+
# Obtener máscaras, probabilidades y clases
|
32 |
+
masks = result.masks.data.cpu().numpy()
|
33 |
+
confidences = result.boxes.conf.cpu().numpy()
|
34 |
classes = result.boxes.cls.cpu().numpy().astype(int)
|
35 |
+
names = model.names
|
36 |
|
37 |
+
# Normalizar probabilidades al rango [0, 1]
|
38 |
confidences_norm = (confidences - confidences.min()) / (confidences.max() - confidences.min() + 1e-6)
|
39 |
|
40 |
# Redimensionar las máscaras para que coincidan con el tamaño de la imagen
|
|
|
42 |
for mask in masks:
|
43 |
mask_resized = cv2.resize(mask, (img.shape[1], img.shape[0]), interpolation=cv2.INTER_LINEAR)
|
44 |
resized_masks.append(mask_resized)
|
45 |
+
resized_masks = np.array(resized_masks)
|
46 |
|
47 |
# Aplicar suavizado a las máscaras
|
48 |
smoothed_masks = []
|
49 |
for mask in resized_masks:
|
|
|
50 |
mask_uint8 = (mask * 255).astype(np.uint8)
|
51 |
+
blurred_mask = cv2.GaussianBlur(mask_uint8, (5, 5), 0)
|
|
|
|
|
52 |
mask_smoothed = blurred_mask.astype(np.float32) / 255.0
|
53 |
smoothed_masks.append(mask_smoothed)
|
54 |
smoothed_masks = np.array(smoothed_masks)
|
55 |
|
56 |
+
# Ordenar máscaras por probabilidad
|
57 |
sorted_indices = np.argsort(-confidences)
|
58 |
sorted_masks = smoothed_masks[sorted_indices]
|
59 |
sorted_confidences = confidences[sorted_indices]
|
60 |
sorted_confidences_norm = confidences_norm[sorted_indices]
|
61 |
sorted_classes = classes[sorted_indices]
|
62 |
|
63 |
+
# Definir mapa de colores con un ajuste para colores más suaves
|
64 |
colormap = plt.cm.get_cmap('viridis')
|
65 |
|
66 |
+
# Procesar cada máscara
|
|
|
|
|
|
|
67 |
for idx_in_order, (idx, mask, conf_norm, conf, cls) in enumerate(zip(sorted_indices, sorted_masks, sorted_confidences_norm, sorted_confidences, sorted_classes)):
|
68 |
+
mask_bool = mask > 0.5
|
69 |
+
update_mask = np.logical_and(mask_bool, mask_image[:, :, 0] == 0) # Solo actualizamos píxeles que no han sido coloreados
|
70 |
+
|
71 |
if not np.any(update_mask):
|
72 |
+
continue
|
|
|
73 |
|
74 |
+
# Obtener color y hacerlo más suave
|
75 |
color_rgb = colormap(conf_norm)[:3]
|
76 |
+
color_rgb = [int(c * 150) for c in color_rgb] # Reducir la intensidad del color (150 en lugar de 255)
|
77 |
+
color_bgr = color_rgb[::-1] # Convertir de RGB a BGR para OpenCV
|
78 |
|
79 |
# Almacenar la información de la máscara
|
80 |
mask_info = {
|
|
|
88 |
|
89 |
# Asignar colores a los píxeles correspondientes en la imagen de máscaras
|
90 |
for i in range(3):
|
91 |
+
mask_image[:, :, i][update_mask] = color_bgr[i]
|
92 |
|
93 |
+
# Superponer la imagen de máscaras sobre la imagen original con transparencia
|
|
|
94 |
img_with_masks = cv2.addWeighted(img.astype(np.float32), 1, mask_image.astype(np.float32), alpha, 0).astype(np.uint8)
|
95 |
|
96 |
else:
|
|
|
97 |
img_with_masks = img.copy()
|
|
|
98 |
|
99 |
+
# Convertir la imagen a RGB para matplotlib
|
100 |
+
img_rgb = cv2.cvtColor(img_with_masks, cv2.COLOR_BGR2RGB)
|
|
|
101 |
|
102 |
+
# Crear una figura para mostrar la imagen y la leyenda
|
103 |
fig, ax = plt.subplots(figsize=(8, 8))
|
104 |
+
ax.imshow(img_rgb)
|
105 |
ax.axis('off')
|
106 |
|
107 |
# Crear la leyenda si hay máscaras detectadas
|
108 |
if mask_info_list:
|
|
|
109 |
handles = []
|
110 |
labels = []
|
111 |
for mask_info in mask_info_list:
|
112 |
+
color_rgb = np.array(mask_info['color_rgb']) / 255 # Normalizar el color
|
113 |
+
patch = Patch(facecolor=color_rgb)
|
|
|
114 |
label = f"{mask_info['class']}: {mask_info['confidence']:.2f}"
|
115 |
handles.append(patch)
|
116 |
labels.append(label)
|
117 |
|
|
|
118 |
ax.legend(handles, labels, loc='upper right')
|
119 |
|
120 |
+
# Convertir la figura a una imagen NumPy
|
121 |
fig.canvas.draw()
|
122 |
img_figure = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
|
123 |
img_figure = img_figure.reshape(fig.canvas.get_width_height()[::-1] + (3,))
|