jarondon82/ComputerVisionProject
1
1import cv22import numpy as np3 4def detect_face_dnn(net, frame, conf_threshold=0.5):5 """6 Detecta rostros en una imagen utilizando un modelo DNN pre-entrenado7 y devuelve los cuadros delimitadores.8 """9 frameHeight = frame.shape[0]10 frameWidth = frame.shape[1]11 12 # Crear un blob a partir de la imagen13 blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300), [104, 117, 123], False, False)14 15 # Establecer la entrada para la red neuronal16 net.setInput(blob)17 18 # Ejecutar la detección19 detections = net.forward()20 21 bboxes = []22 23 # Procesar las detecciones24 for i in range(detections.shape[2]):25 confidence = detections[0, 0, i, 2]26 27 # Filtrar por umbral de confianza28 if confidence > conf_threshold:29 x1 = int(detections[0, 0, i, 3] * frameWidth)30 y1 = int(detections[0, 0, i, 4] * frameHeight)31 x2 = int(detections[0, 0, i, 5] * frameWidth)32 y2 = int(detections[0, 0, i, 6] * frameHeight)33 34 # Asegurarse de que las coordenadas están dentro de los límites de la imagen35 x1 = max(0, min(x1, frameWidth - 1))36 y1 = max(0, min(y1, frameHeight - 1))37 x2 = max(0, min(x2, frameWidth - 1))38 y2 = max(0, min(y2, frameHeight - 1))39 40 # Agregar los cuadros delimitadores y la confianza41 bboxes.append([x1, y1, x2, y2, confidence])42 43 return np.array(bboxes)44 45def main():46 # Cargar el modelo de detección de rostros47 modelFile = "models/opencv_face_detector_uint8.pb"48 configFile = "models/opencv_face_detector.pbtxt"49 net = cv2.dnn.readNetFromTensorflow(modelFile, configFile)50 51 # Iniciar la cámara52 cap = cv2.VideoCapture(0)53 54 if not cap.isOpened():55 print("Error: No se pudo abrir la cámara.")56 return57 58 print("Cámara iniciada correctamente. Presione 'q' para salir.")59 60 while True:61 # Leer un frame de la cámara62 ret, frame = cap.read()63 64 if not ret:65 print("Error al capturar el frame.")66 break67 68 # Detectar rostros con umbrales de confianza diferentes69 for threshold in [0.5, 0.3, 0.1]:70 bboxes = detect_face_dnn(net, frame, threshold)71 72 # Crear copia del frame para dibujar en ella73 display_frame = frame.copy()74 75 # Dibujar los cuadros delimitadores76 for i, bbox in enumerate(bboxes):77 x1, y1, x2, y2, conf = bbox78 # Usar color verde79 color = (0, 255, 0)80 # Dibujar el rectángulo81 cv2.rectangle(display_frame, (int(x1), int(y1)), (int(x2), int(y2)), color, 2)82 # Mostrar la confianza83 label = f"Rostro: {conf:.2f}"84 cv2.putText(display_frame, label, (int(x1), int(y1) - 10), 85 cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)86 87 # Mostrar el número de rostros detectados en la esquina88 cv2.putText(display_frame, f"Umbral: {threshold} - Rostros: {len(bboxes)}", 89 (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)90 91 # Mostrar el resultado92 window_name = f"Detección de Rostros (Umbral: {threshold})"93 cv2.imshow(window_name, display_frame)94 95 # Salir si se presiona 'q'96 if cv2.waitKey(1) & 0xFF == ord('q'):97 break98 99 # Liberar recursos100 cap.release()101 cv2.destroyAllWindows()102 103if __name__ == "__main__":104 main() 