File size: 6,557 Bytes
7306a70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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()