manuelvaraletai commited on
Commit
359da82
·
verified ·
1 Parent(s): 7a88557

Update models/visualizer.py

Browse files
Files changed (1) hide show
  1. models/visualizer.py +22 -83
models/visualizer.py CHANGED
@@ -42,93 +42,32 @@ class TrafficVisualizer:
42
  return (len(text) * 10, 16) # Fallback básico
43
 
44
  def draw_detections(self, frame, detections, metrics):
45
- """Versión optimizada y robusta para visualización"""
46
- print(f"[VISUALIZER] Recibió {len(detections)} detecciones") # Debug
47
- for i, det in enumerate(detections[:3]): # Mostrar las primeras 3
48
- print(f" - Det {i}: {det.get('label')} @ {det.get('bbox')}")
49
-
50
  try:
51
- # Conversión a PIL Image
52
  frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
53
  image = Image.fromarray(frame_rgb)
54
- draw = ImageDraw.Draw(image, 'RGBA') # Modo RGBA para soportar transparencia
55
-
56
- # Dibujar cada detección
57
  for det in detections:
58
- try:
59
- # Extracción de datos
60
- class_name = det.get('label', det.get('class', 'unknown')).lower()
61
- confidence = det.get('confidence', 0.0)
62
-
63
- # Obtención de coordenadas
64
- if 'bbox' in det:
65
- x1, y1, x2, y2 = map(int, det['bbox'])
66
- elif 'box' in det:
67
- box = det['box']
68
- x1 = int(box['x_center'] - box['width']/2)
69
- y1 = int(box['y_center'] - box['height']/2)
70
- x2 = int(box['x_center'] + box['width']/2)
71
- y2 = int(box['y_center'] + box['height']/2)
72
- else:
73
- continue
74
-
75
- # Color basado en clase
76
- color = self.color_map.get(class_name, self.color_map['default'])
77
-
78
- # Dibujar bounding box
79
- draw.rectangle([x1, y1, x2, y2], outline=color, width=3)
80
-
81
- # Dibujar etiqueta con fondo
82
- label = f"{class_name} {confidence:.2f}"
83
- text_w, text_h = self._get_text_size(label)
84
-
85
- # Fondo semi-transparente
86
- draw.rectangle(
87
- [x1, y1-text_h-4, x1+text_w+4, y1],
88
- fill=(*color, self.font_bg_opacity)
89
- )
90
-
91
- # Texto
92
- draw.text(
93
- (x1+2, y1-text_h-2),
94
- label,
95
- fill=self.font_color,
96
- font=self.font
97
- )
98
-
99
- except Exception as e:
100
- print(f"[VISUALIZER WARNING] Error en detección: {str(e)}")
101
- continue
102
-
103
- # Dibujar métricas
104
- metrics_text = [
105
- f"Objetos: {metrics.get('total_objects', 0)}",
106
- f"Caos: {metrics.get('chaos_score', 0.0):.2f}",
107
- f"Densidad: {metrics.get('density_score', 0.0):.2f}"
108
- ]
109
-
110
- y_offset = 10
111
- for text in metrics_text:
112
- text_w, text_h = self._get_text_size(text)
113
-
114
- # Fondo negro semi-transparente
115
- draw.rectangle(
116
- [10, y_offset, 20+text_w, y_offset+text_h+10],
117
- fill=(0, 0, 0, self.font_bg_opacity)
118
- )
119
-
120
- # Texto blanco
121
- draw.text(
122
- (15, y_offset+5),
123
- text,
124
- fill="white",
125
- font=self.font
126
- )
127
- y_offset += text_h + 15
128
-
129
- # Convertir de vuelta a OpenCV
130
- return cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
131
-
132
  except Exception as e:
133
  print(f"[VISUALIZER ERROR] {str(e)}")
134
  return frame
 
42
  return (len(text) * 10, 16) # Fallback básico
43
 
44
  def draw_detections(self, frame, detections, metrics):
 
 
 
 
 
45
  try:
46
+ # Convertir frame OpenCV (BGR) a PIL (RGB)
47
  frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
48
  image = Image.fromarray(frame_rgb)
49
+ draw = ImageDraw.Draw(image, 'RGBA')
50
+ height, width = frame.shape[:2]
51
+
52
  for det in detections:
53
+ # Escalar coordenadas normalizadas a absolutas
54
+ x1 = int(det['bbox'][0] * width)
55
+ y1 = int(det['bbox'][1] * height)
56
+ x2 = int(det['bbox'][2] * width)
57
+ y2 = int(det['bbox'][3] * height)
58
+
59
+ # Dibujar bounding box
60
+ color = self.color_map.get(det['label'].lower(), self.color_map['default'])
61
+ draw.rectangle([x1, y1, x2, y2], outline=color, width=3)
62
+
63
+ # Dibujar etiqueta
64
+ label = f"{det['label']} {det['confidence']:.2f}"
65
+ text_w, text_h = self._get_text_size(label)
66
+ draw.rectangle([x1, y1-text_h-4, x1+text_w+4, y1], fill=(*color, 128))
67
+ draw.text((x1+2, y1-text_h-2), label, fill="black", font=self.font)
68
+
69
+ return cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) # Convertir a BGR para OpenCV
70
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  except Exception as e:
72
  print(f"[VISUALIZER ERROR] {str(e)}")
73
  return frame