import cv2 import numpy as np import os import sys from pathlib import Path from typing import Optional from datetime import datetime import warnings # Suprimir advertencia de PyTorch 2.5 sobre torch.load() para mantener la terminal limpia warnings.filterwarnings("ignore", category=FutureWarning, module="torch") # Importación lazy para no fallar si ultralytics no está instalado en tiempo de import try: from ultralytics import YOLO YOLO_AVAILABLE = True except ImportError: YOLO_AVAILABLE = False # Clase única para detectar: persona (class_id = 0 en COCO) PERSON_CLASS_ID = 0 # Colores BGR COLOR_BOX_NORMAL = (0, 255, 0) # verde COLOR_BOX_ALERT = (0, 0, 255) # rojo COLOR_ZONE_NORMAL = (0, 165, 255) # naranja COLOR_ZONE_ALERT = (0, 0, 255) # rojo COLOR_TEXT = (255, 255, 255) # blanco COLOR_TEXT_SHADOW = (0, 0, 0) # negro # Conexiones del esqueleto (COCO format) — constante a nivel de módulo SKELETON_CONNECTIONS = ( (15, 13), (13, 11), (16, 14), (14, 12), (11, 12), (5, 11), (6, 12), (5, 6), (5, 7), (6, 8), (7, 9), (8, 10), (1, 2), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6), ) # Detección de entorno _IS_CLOUD = sys.platform.startswith("linux") class PersonDetector: """ Encapsula el modelo YOLOv8 y la lógica de detección de personas. """ def __init__(self, model_name: str = "yolov8n-pose.pt", confidence: float = 0.75): """ Args: model_name: Nombre del modelo YOLOv8 a cargar. confidence: Umbral mínimo de confianza para aceptar una detección. """ if not YOLO_AVAILABLE: raise ImportError( "ultralytics no está instalado. Ejecuta: pip install ultralytics" ) self.confidence = confidence self.model = YOLO(model_name) # Resolución de inferencia adaptativa: # - Nube (CPU): 320px — duplica velocidad, YOLO mapea coordenadas de vuelta al original # - Local (GPU): 640px — máxima precisión self._pose_imgsz = 320 if _IS_CLOUD else 640 # Precalentamiento del modelo dummy = np.zeros((480, 640, 3), dtype=np.uint8) self.model(dummy, verbose=False, imgsz=self._pose_imgsz) # Cargar modelo de anomalías si existe (El "Cerebro 2") self.anomaly_model = None self._anomaly_imgsz = 224 # Entrenado a 224px — respetar resolución de entrenamiento # Frame-skip del modelo de anomalías: # No es necesario clasificar cada frame. Correr cada N frames ahorra # 50-150ms por frame en CPU sin perder calidad de detección. self._anomaly_run_every = 6 if _IS_CLOUD else 3 self._anomaly_frame_count = 0 self._last_anomaly_info = None # Cache del último resultado anomaly_path = "runs/classify/servsecurity_anomaly_model/weights/best.pt" if os.path.exists(anomaly_path): self.anomaly_model = YOLO(anomaly_path) self.anomaly_model(dummy, verbose=False, imgsz=self._anomaly_imgsz) # Precalentamiento print("✅ Modelo de Anomalías cargado con éxito.") def detect(self, frame: np.ndarray) -> tuple[list[dict], Optional[dict]]: # 1. MOTOR 1: Detección de Personas (Pose) results = self.model( frame, verbose=False, conf=self.confidence, classes=[PERSON_CLASS_ID], imgsz=self._pose_imgsz, ) detections = [] for result in results: boxes = result.boxes keypoints = result.keypoints if boxes is None: continue for i, box in enumerate(boxes): x1, y1, x2, y2 = map(int, box.xyxy[0].tolist()) conf = float(box.conf[0]) cx = (x1 + x2) // 2 cy = (y1 + y2) // 2 # Extraer keypoints si el modelo lo soporta (yolov8-pose) kpts = None if keypoints is not None and len(keypoints) > i: # kpts: (17, 3) donde [2] es la confianza del keypoint # Usamos .data[0] para obtener el tensor de la persona actual kpt_data = keypoints.data[i].cpu().numpy() kpts = kpt_data.tolist() # Filtro anti-alucinaciones (motos, macetas, objetos complejos): # Una moto puede engañar a la IA y generar keypoints con ~0.5 de confianza. # Exigimos al menos 5 puntos anatómicos con una certeza MUY alta (> 0.70). valid_kpts = sum(1 for kp in kpts if len(kp) >= 3 and kp[2] > 0.70) if valid_kpts < 5: continue # Descartar esta detección, es muy probable que sea un objeto # --- Lógica de Recorte de Cabeza (Head Crop) para mejor reconocimiento --- head_crop = None if kpts is not None and len(kpts) >= 5: # Extraer keypoints faciales (0: nariz, 1: ojo izq, 2: ojo der, 3: oreja izq, 4: oreja der) face_kpts = [kp for kp in kpts[:5] if len(kp) >= 3 and kp[2] > 0.4] if len(face_kpts) >= 2: fx_min = int(min(kp[0] for kp in face_kpts)) fy_min = int(min(kp[1] for kp in face_kpts)) fx_max = int(max(kp[0] for kp in face_kpts)) fy_max = int(max(kp[1] for kp in face_kpts)) # Añadir margen alrededor de la cara w = max(fx_max - fx_min, 10) h = max(fy_max - fy_min, 10) pad_x = int(w * 1.5) pad_y = int(h * 1.5) hx1 = max(0, fx_min - pad_x) hy1 = max(0, fy_min - pad_y * 1.5) hx2 = min(frame.shape[1], fx_max + pad_x) hy2 = min(frame.shape[0], fy_max + pad_y) head_crop = frame[int(hy1):int(hy2), int(hx1):int(hx2)].copy() # Fallback: Si no hay keypoints faciales fiables, tomar el 30% superior del cuerpo if head_crop is None or head_crop.size == 0: head_h = int((y2 - y1) * 0.3) head_crop = frame[y1:y1+head_h, x1:x2].copy() detections.append({ "bbox": (x1, y1, x2, y2), "confidence": conf, "center": (cx, cy), "keypoints": kpts, "crop": head_crop }) # 2. MOTOR 2: Clasificación de Anomalías (frame-skipping adaptativo) # Solo se ejecuta cada N frames para ahorrar CPU, reutilizando el # último resultado conocido en los frames intermedios. self._anomaly_frame_count += 1 run_anomaly = ( self.anomaly_model is not None and len(detections) > 0 and self._anomaly_frame_count % self._anomaly_run_every == 0 ) if run_anomaly: cls_results = self.anomaly_model( frame, verbose=False, imgsz=self._anomaly_imgsz, ) anomaly_info = None if cls_results and len(cls_results) > 0: probs = cls_results[0].probs if probs is not None: top_class_idx = probs.top1 top_conf = float(probs.top1conf) top_class_name = cls_results[0].names[top_class_idx] if top_class_name.lower() != "normal" and top_conf > 0.70: anomaly_info = { "class": top_class_name.upper(), "conf": top_conf, } self._last_anomaly_info = anomaly_info else: # Reutilizar el último resultado conocido anomaly_info = self._last_anomaly_info # Si ya no hay personas en el frame, limpiar el cache de anomalía if len(detections) == 0: self._last_anomaly_info = None anomaly_info = None return detections, anomaly_info def draw_detections( frame: np.ndarray, detections: list[dict], alerts: list[bool], zone: Optional[tuple] = None, zone_active: bool = True, draw_skeleton: bool = True, anomaly_info: Optional[dict] = None ) -> np.ndarray: """ Dibuja las bounding boxes, estado de alerta, zona restringida y anomalías globales. Args: frame: Imagen BGR original. detections: Lista de detecciones del detector. alerts: Lista booleana paralela a detections (True = alerta activa). zone: Tupla (x1, y1, x2, y2) de la zona restringida. zone_active: Si True, muestra la zona restringida. draw_skeleton: Si True, dibuja el esqueleto de la persona. anomaly_info: Diccionario con info de la anomalía global detectada, o None. Returns: Frame anotado. """ output = frame.copy() h, w = output.shape[:2] # ── Zona restringida ────────────────────────────────────────────────────── if zone_active and zone is not None: zx1, zy1, zx2, zy2 = zone any_alert = any(alerts) if alerts else False zone_color = COLOR_ZONE_ALERT if any_alert else COLOR_ZONE_NORMAL # Overlay semitransparente — solo sobre la sub-región de la zona (ROI) # En vez de copiar todo el frame, operamos solo sobre la zona restringida roi = output[zy1:zy2, zx1:zx2] overlay_roi = roi.copy() overlay_roi[:] = zone_color cv2.addWeighted(overlay_roi, 0.15, roi, 0.85, 0, roi) cv2.rectangle(output, (zx1, zy1), (zx2, zy2), zone_color, 2) # Etiqueta de zona label = "ZONA RESTRINGIDA" (lw, lh), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2) cv2.rectangle(output, (zx1, zy1 - lh - 8), (zx1 + lw + 8, zy1), zone_color, -1) cv2.putText(output, label, (zx1 + 4, zy1 - 4), cv2.FONT_HERSHEY_SIMPLEX, 0.6, COLOR_TEXT, 2) # ── Bounding boxes de personas ──────────────────────────────────────────── for i, det in enumerate(detections): x1, y1, x2, y2 = det["bbox"] conf = det["confidence"] is_alert = alerts[i] if i < len(alerts) else False box_color = COLOR_BOX_ALERT if is_alert else COLOR_BOX_NORMAL auth_status = det.get("is_authorized") if auth_status is True: auth_text = " [AUTORIZADO]" box_color = (255, 165, 0) # Celeste/Verde claro si esta autorizado elif auth_status is False: auth_text = " [DESCONOCIDO]" box_color = COLOR_BOX_ALERT # Rojo si es desconocido else: auth_text = " [Analizando...]" status_text = "[!] ALERTA" if is_alert else "Persona" label = f"{status_text}{auth_text} {conf:.0%}" # Caja cv2.rectangle(output, (x1, y1), (x2, y2), box_color, 2) # Etiqueta con fondo (lw, lh), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.55, 2) cv2.rectangle(output, (x1, y1 - lh - 8), (x1 + lw + 6, y1), box_color, -1) cv2.putText(output, label, (x1 + 3, y1 - 4), cv2.FONT_HERSHEY_SIMPLEX, 0.55, COLOR_TEXT, 2) # ── Dibujar Esqueleto (Keypoints) ───────────────────────────────────── kpts = det.get("keypoints") if kpts is not None and draw_skeleton: # Dibujar uniones (huesos) — usa constante de módulo for j1, j2 in SKELETON_CONNECTIONS: if j1 < len(kpts) and j2 < len(kpts): p1 = kpts[j1] p2 = kpts[j2] # Validar si tienen confianza > 0.5 (si la confianza existe en kpts[i][2]) if (len(p1) > 2 and p1[2] < 0.5) or (len(p2) > 2 and p2[2] < 0.5): continue if p1[0] == 0 or p2[0] == 0: # Keypoints no detectados continue pt1 = (int(p1[0]), int(p1[1])) pt2 = (int(p2[0]), int(p2[1])) # Dibujar linea semitransparente cv2.line(output, pt1, pt2, box_color, 2) # Dibujar puntos (articulaciones) for p in kpts: if p[0] != 0 and p[1] != 0: if len(p) > 2 and p[2] < 0.5: continue cv2.circle(output, (int(p[0]), int(p[1])), 3, (0, 255, 255), -1) # Punto central cx, cy = det["center"] cv2.circle(output, (cx, cy), 5, box_color, -1) # ── Timestamp en esquina ────────────────────────────────────────────────── ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S") cv2.putText(output, ts, (10, h - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLOR_TEXT_SHADOW, 3) cv2.putText(output, ts, (10, h - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLOR_TEXT, 1) # ── Marca de agua ───────────────────────────────────────────────────────── cv2.putText(output, "SERVSecurity v1.0", (10, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (180, 220, 255), 1) # ── Alerta Global de Anomalía ───────────────────────────────────────────── if anomaly_info is not None: anomaly_text = f"¡ALERTA CRITICA: {anomaly_info['class']} DETECTADO! ({anomaly_info['conf']:.0%})" (tw, th), _ = cv2.getTextSize(anomaly_text, cv2.FONT_HERSHEY_DUPLEX, 0.8, 2) tx = (w - tw) // 2 ty = 50 # Fondo rojo sangriento con borde negro cv2.rectangle(output, (tx - 20, ty - th - 15), (tx + tw + 20, ty + 15), (0, 0, 255), -1) cv2.rectangle(output, (tx - 20, ty - th - 15), (tx + tw + 20, ty + 15), (0, 0, 0), 2) # Texto blanco con sombra cv2.putText(output, anomaly_text, (tx+2, ty+2), cv2.FONT_HERSHEY_DUPLEX, 0.8, (0, 0, 0), 2) cv2.putText(output, anomaly_text, (tx, ty), cv2.FONT_HERSHEY_DUPLEX, 0.8, (255, 255, 255), 2) return output