import cv2 import numpy as np from typing import Optional, Tuple, List class FaceDetector: """Face detection utility with multiple detection strategies.""" def __init__(self): """Initialize the face detector with multiple Haar Cascade classifiers.""" # Primary detector - frontal face self.face_cascade = cv2.CascadeClassifier( cv2.data.haarcascades + 'haarcascade_frontalface_default.xml' ) # Alternative detector - frontal face alt self.face_cascade_alt = cv2.CascadeClassifier( cv2.data.haarcascades + 'haarcascade_frontalface_alt.xml' ) # Another alternative - frontal face alt2 self.face_cascade_alt2 = cv2.CascadeClassifier( cv2.data.haarcascades + 'haarcascade_frontalface_alt2.xml' ) def _detect_with_cascade( self, gray: np.ndarray, cascade: cv2.CascadeClassifier, scale_factor: float = 1.1, min_neighbors: int = 3, min_size: Tuple[int, int] = (20, 20) ) -> List: """Detect faces using a specific cascade classifier.""" try: faces = cascade.detectMultiScale( gray, scaleFactor=scale_factor, minNeighbors=min_neighbors, minSize=min_size, flags=cv2.CASCADE_SCALE_IMAGE ) return list(faces) if len(faces) > 0 else [] except Exception: return [] def detect_and_crop_face( self, image: np.ndarray, target_size: Tuple[int, int] = (224, 224), padding: float = 0.2 ) -> Optional[np.ndarray]: """ Detect face in image and crop it with padding. Uses multiple detection strategies for robustness. Args: image: Input image as numpy array (BGR format from OpenCV) target_size: Target size for the cropped face (width, height) padding: Padding ratio to add around the detected face Returns: Cropped and resized face image, or None if no face detected """ if image is None or image.size == 0: print("Warning: Empty or invalid image received") return None # Convert to grayscale try: if len(image.shape) == 2: gray = image else: gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) except Exception as e: print(f"Warning: Failed to convert to grayscale: {e}") return None # Enhance contrast for better detection gray = cv2.equalizeHist(gray) faces = [] # Strategy 1: Primary cascade with standard parameters faces = self._detect_with_cascade(gray, self.face_cascade, 1.1, 5, (30, 30)) # Strategy 2: Primary cascade with more lenient parameters if len(faces) == 0: faces = self._detect_with_cascade(gray, self.face_cascade, 1.05, 3, (20, 20)) # Strategy 3: Alt cascade if len(faces) == 0: faces = self._detect_with_cascade(gray, self.face_cascade_alt, 1.1, 3, (20, 20)) # Strategy 4: Alt2 cascade if len(faces) == 0: faces = self._detect_with_cascade(gray, self.face_cascade_alt2, 1.1, 3, (20, 20)) # Strategy 5: Very lenient detection if len(faces) == 0: faces = self._detect_with_cascade(gray, self.face_cascade, 1.02, 2, (15, 15)) # Strategy 6: Try with different image sizes if len(faces) == 0: # Try with scaled up image scale = 1.5 scaled = cv2.resize(gray, None, fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR) faces = self._detect_with_cascade(scaled, self.face_cascade, 1.1, 3, (30, 30)) if len(faces) > 0: # Scale coordinates back faces = [(int(x/scale), int(y/scale), int(w/scale), int(h/scale)) for (x, y, w, h) in faces] # Strategy 7: If still no face, use the entire image as the face region # This is a fallback for cases where face detection fails but user insists image has a face if len(faces) == 0: print("Warning: No face detected with any strategy. Using center crop as fallback.") h, w = image.shape[:2] # Use center 70% of the image margin_w = int(w * 0.15) margin_h = int(h * 0.15) face_crop = image[margin_h:h-margin_h, margin_w:w-margin_w] if face_crop.size > 0: face_resized = cv2.resize(face_crop, target_size, interpolation=cv2.INTER_AREA) if len(face_resized.shape) == 3: face_rgb = cv2.cvtColor(face_resized, cv2.COLOR_BGR2RGB) else: face_rgb = cv2.cvtColor(face_resized, cv2.COLOR_GRAY2RGB) return face_rgb return None # Get the largest face x, y, w, h = max(faces, key=lambda f: f[2] * f[3]) # Add padding pad_w = int(w * padding) pad_h = int(h * padding) img_h, img_w = image.shape[:2] x1 = max(0, x - pad_w) y1 = max(0, y - pad_h) x2 = min(img_w, x + w + pad_w) y2 = min(img_h, y + h + pad_h) face_crop = image[y1:y2, x1:x2] if face_crop.size == 0: return None face_resized = cv2.resize(face_crop, target_size, interpolation=cv2.INTER_AREA) # Convert to RGB if len(face_resized.shape) == 3: face_rgb = cv2.cvtColor(face_resized, cv2.COLOR_BGR2RGB) else: face_rgb = cv2.cvtColor(face_resized, cv2.COLOR_GRAY2RGB) return face_rgb def detect_faces_count(self, image: np.ndarray) -> int: """ Count number of faces detected in image. Args: image: Input image as numpy array Returns: Number of faces detected """ try: gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.equalizeHist(gray) faces = self._detect_with_cascade(gray, self.face_cascade, 1.1, 3, (20, 20)) return len(faces) except Exception: return 0 face_detector = FaceDetector()