File size: 1,801 Bytes
1d20984
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)