PavaniYerra commited on
Commit
da26386
Β·
1 Parent(s): 16afa08
app/Hackathon_setup/__pycache__/face_recognition.cpython-313.pyc CHANGED
Binary files a/app/Hackathon_setup/__pycache__/face_recognition.cpython-313.pyc and b/app/Hackathon_setup/__pycache__/face_recognition.cpython-313.pyc differ
 
app/Hackathon_setup/analyze_face_detection.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Analyze face detection issues and improve face recognition pipeline
3
+ """
4
+
5
+ import os
6
+ import sys
7
+ import numpy as np
8
+ import cv2
9
+ from PIL import Image
10
+
11
+ print("πŸ” Face Detection Analysis & Improvement")
12
+ print("=" * 50)
13
+
14
+ def analyze_face_detection_issue():
15
+ """Analyze why face detection is failing"""
16
+
17
+ print("πŸ“Š Current Issue Analysis:")
18
+ print(" - Logs show: 'No faces detected, using fallback'")
19
+ print(" - This means OpenCV face detection is failing")
20
+ print(" - System falls back to using entire image")
21
+ print(" - Classification still works but may be less accurate")
22
+ print()
23
+
24
+ print("πŸ” Possible Causes:")
25
+ print(" 1. Face cascade file issues")
26
+ print(" 2. Image quality/resolution problems")
27
+ print(" 3. Face detection parameters too strict")
28
+ print(" 4. Images don't contain clear frontal faces")
29
+ print(" 5. Cascade classifier not loading properly")
30
+ print()
31
+
32
+ def check_cascade_files():
33
+ """Check if cascade files are working properly"""
34
+
35
+ print("πŸ”§ Checking Cascade Files...")
36
+
37
+ cascade_files = [
38
+ 'haarcascade_frontalface_default.xml',
39
+ 'haarcascade_eye.xml'
40
+ ]
41
+
42
+ for file in cascade_files:
43
+ if os.path.exists(file):
44
+ size = os.path.getsize(file)
45
+ print(f" βœ“ {file} exists ({size:,} bytes)")
46
+
47
+ # Test loading
48
+ try:
49
+ cascade = cv2.CascadeClassifier(file)
50
+ if cascade.empty():
51
+ print(f" ❌ {file} failed to load properly")
52
+ else:
53
+ print(f" βœ… {file} loaded successfully")
54
+ except Exception as e:
55
+ print(f" ❌ Error loading {file}: {e}")
56
+ else:
57
+ print(f" ❌ {file} missing")
58
+
59
+ def improve_face_detection():
60
+ """Improve the face detection function"""
61
+
62
+ print("\nπŸ”§ Improving Face Detection...")
63
+
64
+ # Create improved face detection function
65
+ improved_code = '''
66
+ def improved_detected_face(image):
67
+ """Improved face detection with better parameters"""
68
+ eye_haar = current_path + '/haarcascade_eye.xml'
69
+ face_haar = current_path + '/haarcascade_frontalface_default.xml'
70
+
71
+ # Check if cascade files exist
72
+ if not os.path.exists(face_haar):
73
+ print(f"Warning: {face_haar} not found, using fallback")
74
+ return Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY))
75
+
76
+ face_cascade = cv2.CascadeClassifier(face_haar)
77
+ eye_cascade = cv2.CascadeClassifier(eye_haar) if os.path.exists(eye_haar) else None
78
+
79
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
80
+
81
+ # Try multiple detection parameters for better results
82
+ detection_params = [
83
+ (1.1, 3), # Default
84
+ (1.05, 4), # More sensitive
85
+ (1.2, 2), # Less sensitive but faster
86
+ (1.3, 5) # Very sensitive
87
+ ]
88
+
89
+ faces = []
90
+ for scale_factor, min_neighbors in detection_params:
91
+ faces = face_cascade.detectMultiScale(
92
+ gray,
93
+ scaleFactor=scale_factor,
94
+ minNeighbors=min_neighbors,
95
+ minSize=(30, 30), # Minimum face size
96
+ maxSize=(300, 300) # Maximum face size
97
+ )
98
+ if len(faces) > 0:
99
+ print(f"βœ“ Faces detected with scaleFactor={scale_factor}, minNeighbors={min_neighbors}")
100
+ break
101
+
102
+ # If still no faces, try with different image preprocessing
103
+ if len(faces) == 0:
104
+ print("No faces detected with standard parameters, trying preprocessing...")
105
+
106
+ # Try histogram equalization
107
+ gray_eq = cv2.equalizeHist(gray)
108
+ faces = face_cascade.detectMultiScale(gray_eq, 1.1, 3)
109
+
110
+ if len(faces) == 0:
111
+ # Try Gaussian blur
112
+ gray_blur = cv2.GaussianBlur(gray, (3, 3), 0)
113
+ faces = face_cascade.detectMultiScale(gray_blur, 1.1, 3)
114
+
115
+ if len(faces) == 0:
116
+ print("No faces detected after all attempts, using fallback")
117
+ return None
118
+
119
+ # Find the largest face
120
+ face_areas = []
121
+ images = []
122
+
123
+ for i, (x, y, w, h) in enumerate(faces):
124
+ face_cropped = gray[y:y+h, x:x+w]
125
+ face_areas.append(w*h)
126
+ images.append(face_cropped)
127
+
128
+ # Get the largest face
129
+ largest_face_idx = np.argmax(face_areas)
130
+ required_image = Image.fromarray(images[largest_face_idx])
131
+
132
+ print(f"βœ“ Selected face {largest_face_idx + 1} of {len(faces)} detected faces")
133
+
134
+ return required_image
135
+ '''
136
+
137
+ print("βœ… Improved face detection function created")
138
+ print(" - Multiple detection parameters")
139
+ print(" - Image preprocessing options")
140
+ print(" - Better error handling")
141
+ print(" - More detailed logging")
142
+
143
+ def create_face_detection_test():
144
+ """Create a test to verify face detection"""
145
+
146
+ print("\nπŸ§ͺ Creating Face Detection Test...")
147
+
148
+ test_code = '''
149
+ def test_face_detection():
150
+ """Test face detection with sample images"""
151
+
152
+ # Test with actual image if available
153
+ test_paths = [
154
+ "../static/Person1_1697805233.jpg",
155
+ "Person1_1697805233.jpg",
156
+ "static/Person1_1697805233.jpg"
157
+ ]
158
+
159
+ for path in test_paths:
160
+ if os.path.exists(path):
161
+ print(f"Testing face detection with: {path}")
162
+
163
+ # Load image
164
+ img = cv2.imread(path)
165
+ print(f"Image shape: {img.shape}")
166
+
167
+ # Test face detection
168
+ detected = improved_detected_face(img)
169
+
170
+ if detected is not None:
171
+ print(f"βœ… Face detected successfully: {type(detected)}")
172
+ print(f"Face size: {detected.size}")
173
+ else:
174
+ print("❌ No face detected")
175
+
176
+ break
177
+ else:
178
+ print("No test images found")
179
+
180
+ # Create synthetic face for testing
181
+ print("Creating synthetic face for testing...")
182
+ synthetic_img = np.zeros((200, 200, 3), dtype=np.uint8)
183
+
184
+ # Draw a simple face
185
+ cv2.ellipse(synthetic_img, (100, 100), (80, 100), 0, 0, 360, (120, 120, 120), -1)
186
+ cv2.circle(synthetic_img, (70, 80), 8, (200, 200, 200), -1)
187
+ cv2.circle(synthetic_img, (130, 80), 8, (200, 200, 200), -1)
188
+ cv2.line(synthetic_img, (100, 90), (100, 120), (150, 150, 150), 3)
189
+ cv2.ellipse(synthetic_img, (100, 140), (20, 10), 0, 0, 180, (150, 150, 150), 2)
190
+
191
+ print("Testing with synthetic face...")
192
+ detected = improved_detected_face(synthetic_img)
193
+
194
+ if detected is not None:
195
+ print("βœ… Synthetic face detected successfully")
196
+ else:
197
+ print("❌ Even synthetic face not detected - cascade issue")
198
+ '''
199
+
200
+ print("βœ… Face detection test created")
201
+
202
+ def provide_recommendations():
203
+ """Provide recommendations for better face detection"""
204
+
205
+ print("\nπŸ’‘ Recommendations for Better Face Detection:")
206
+ print()
207
+ print("1. πŸ“Έ Image Quality:")
208
+ print(" - Ensure images have clear, frontal faces")
209
+ print(" - Good lighting and contrast")
210
+ print(" - Face should be clearly visible")
211
+ print(" - Avoid side profiles or partially hidden faces")
212
+ print()
213
+
214
+ print("2. πŸ”§ Detection Parameters:")
215
+ print(" - Try different scaleFactor values (1.05-1.3)")
216
+ print(" - Adjust minNeighbors (2-5)")
217
+ print(" - Set appropriate minSize and maxSize")
218
+ print()
219
+
220
+ print("3. πŸ–ΌοΈ Image Preprocessing:")
221
+ print(" - Histogram equalization for better contrast")
222
+ print(" - Gaussian blur to reduce noise")
223
+ print(" - Resize images to standard size")
224
+ print()
225
+
226
+ print("4. πŸ“Š Training Data Considerations:")
227
+ print(" - Your training used face detection during training")
228
+ print(" - If training images had faces detected, inference should too")
229
+ print(" - Check if training images were preprocessed differently")
230
+ print()
231
+
232
+ print("5. 🎯 Current Status:")
233
+ print(" - βœ… Classification working (Person2 detected)")
234
+ print(" - ⚠️ Face detection failing (using fallback)")
235
+ print(" - βœ… System still functional but may be less accurate")
236
+
237
+ if __name__ == "__main__":
238
+ analyze_face_detection_issue()
239
+ check_cascade_files()
240
+ improve_face_detection()
241
+ create_face_detection_test()
242
+ provide_recommendations()
243
+
244
+ print("\n🎯 Summary:")
245
+ print("Your classification is working correctly (Person2 detected)")
246
+ print("Face detection is failing but system uses fallback")
247
+ print("This may reduce accuracy but doesn't break the system")
248
+ print("Consider improving image quality or detection parameters")
app/Hackathon_setup/face_recognition.py CHANGED
@@ -115,7 +115,7 @@ def safe_load_model(file_path, model_type="joblib"):
115
  raise e
116
 
117
  def detected_face(image):
118
- """Detect face in the given image"""
119
  eye_haar = current_path + '/haarcascade_eye.xml'
120
  face_haar = current_path + '/haarcascade_frontalface_default.xml'
121
 
@@ -128,13 +128,46 @@ def detected_face(image):
128
  eye_cascade = cv2.CascadeClassifier(eye_haar) if os.path.exists(eye_haar) else None
129
 
130
  gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
131
- faces = face_cascade.detectMultiScale(gray, 1.3, 5)
132
 
133
- # If no faces detected, return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  if len(faces) == 0:
135
- print("No faces detected, using fallback")
 
 
 
 
 
 
 
 
 
 
 
 
136
  return None
137
 
 
138
  face_areas = []
139
  images = []
140
 
@@ -147,6 +180,8 @@ def detected_face(image):
147
  largest_face_idx = np.argmax(face_areas)
148
  required_image = Image.fromarray(images[largest_face_idx])
149
 
 
 
150
  return required_image
151
 
152
  def get_similarity(img1, img2):
 
115
  raise e
116
 
117
  def detected_face(image):
118
+ """Improved face detection with multiple parameters and preprocessing"""
119
  eye_haar = current_path + '/haarcascade_eye.xml'
120
  face_haar = current_path + '/haarcascade_frontalface_default.xml'
121
 
 
128
  eye_cascade = cv2.CascadeClassifier(eye_haar) if os.path.exists(eye_haar) else None
129
 
130
  gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
 
131
 
132
+ # Try multiple detection parameters for better results
133
+ detection_params = [
134
+ (1.1, 3), # Default
135
+ (1.05, 4), # More sensitive
136
+ (1.2, 2), # Less sensitive but faster
137
+ (1.3, 5) # Very sensitive
138
+ ]
139
+
140
+ faces = []
141
+ for scale_factor, min_neighbors in detection_params:
142
+ faces = face_cascade.detectMultiScale(
143
+ gray,
144
+ scaleFactor=scale_factor,
145
+ minNeighbors=min_neighbors,
146
+ minSize=(30, 30), # Minimum face size
147
+ maxSize=(300, 300) # Maximum face size
148
+ )
149
+ if len(faces) > 0:
150
+ print(f"βœ“ Faces detected with scaleFactor={scale_factor}, minNeighbors={min_neighbors}")
151
+ break
152
+
153
+ # If still no faces, try with different image preprocessing
154
  if len(faces) == 0:
155
+ print("No faces detected with standard parameters, trying preprocessing...")
156
+
157
+ # Try histogram equalization
158
+ gray_eq = cv2.equalizeHist(gray)
159
+ faces = face_cascade.detectMultiScale(gray_eq, 1.1, 3)
160
+
161
+ if len(faces) == 0:
162
+ # Try Gaussian blur
163
+ gray_blur = cv2.GaussianBlur(gray, (3, 3), 0)
164
+ faces = face_cascade.detectMultiScale(gray_blur, 1.1, 3)
165
+
166
+ if len(faces) == 0:
167
+ print("No faces detected after all attempts, using fallback")
168
  return None
169
 
170
+ # Find the largest face
171
  face_areas = []
172
  images = []
173
 
 
180
  largest_face_idx = np.argmax(face_areas)
181
  required_image = Image.fromarray(images[largest_face_idx])
182
 
183
+ print(f"βœ“ Selected face {largest_face_idx + 1} of {len(faces)} detected faces")
184
+
185
  return required_image
186
 
187
  def get_similarity(img1, img2):