Spaces:
Sleeping
Sleeping
| import cv2 | |
| import numpy as np | |
| from PIL import Image | |
| import gradio as gr | |
| def detect_faces(image): | |
| image_np = np.array(image) | |
| gray_image = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY) | |
| face_cascade = cv2.CascadeClassifier( | |
| cv2.data.haarcascades + "haarcascade_frontalface_default.xml" | |
| ) | |
| scale_factors_found = [] # β store scale factors that detect 14 faces | |
| # Test scale factors from 1.01 to 1.20 | |
| for temp in np.arange(1.01, 1.21, 0.01): | |
| faces = face_cascade.detectMultiScale( | |
| gray_image, | |
| scaleFactor=temp, | |
| minNeighbors=5, | |
| minSize=(20, 20) | |
| ) | |
| if len(faces) == 14: | |
| scale_factors_found.append(round(temp, 2)) | |
| # Draw faces using the last successful scale factor (if any) | |
| if scale_factors_found: | |
| best_scale = scale_factors_found[-1] | |
| faces = face_cascade.detectMultiScale( | |
| gray_image, | |
| scaleFactor=best_scale, | |
| minNeighbors=5, | |
| minSize=(20, 20) | |
| ) | |
| for (x, y, w, h) in faces: | |
| cv2.rectangle(image_np, (x, y), (x + w, y + h), (0, 255, 0), 2) | |
| msg = ( | |
| f"β Found {len(scale_factors_found)} scale factor(s) that detect 14 faces:\n" | |
| f"{scale_factors_found}\n\n" | |
| f"Image displayed uses the last one: {best_scale}" | |
| ) | |
| else: | |
| msg = "β No scale factor between 1.01 and 1.20 detected exactly 14 faces." | |
| return image_np, msg | |
| # --- Gradio Interface --- | |
| iface = gr.Interface( | |
| fn=detect_faces, | |
| inputs=gr.Image(type="pil"), | |
| outputs=["image", "text"], | |
| title="Dynamic Face Detection App", | |
| description="Tests multiple scale factors (1.01β1.20) and shows all that detect exactly 14 faces." | |
| ) | |
| iface.launch(share=True) | |