File size: 2,095 Bytes
5c62f32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e427213
5c62f32
 
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
import cv2
import imutils
import gradio as gr
import numpy as np

face_detector = cv2.CascadeClassifier("haar_cascades/haarcascade_frontalface_default.xml")

def detect_faces(img, size, neighbours, scale):
    frame = np.array(img) 
    frame = frame[:, :, ::-1].copy()
    frame = imutils.resize(frame, width=500)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faceRects = face_detector.detectMultiScale(
        gray, scaleFactor=scale, minNeighbors=neighbours, minSize=(size, size),
        flags=cv2.CASCADE_SCALE_IMAGE)

    box_data = []

    class_labels = {
        0: "face"
    }

    for (x,y,w,h) in faceRects:
        frame = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)

        midX = int(x+w/2)
        midY = int(y+h/2) 
        box = {
                    "position": {
                        "middle": [midX, midY],
                        "width": float(w),
                        "height": float(h)
                    },
                    "domain" : "pixel",
                    "class_id" : 0
                }
        box_data.append(box)

    predictions = {"predictions": {
            "box_data": box_data,
            "class_labels": class_labels
        }
        }

    re_im =cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    return re_im
    
image = gr.components.Image()
out_im = gr.components.Image()

size_slider = gr.components.Slider(minimum=5, maximum=50, value=30, step=5, label="MinSize in Pixel")
neighbour_slider = gr.components.Slider(minimum=1, maximum=20, value=5, step=1, label="Min Number of Neighbours")
scale_slider = gr.components.Slider(minimum=1.1, maximum=2.0, value=1.3, step=0.1, label="Scale Factor")

description = """Face Detection with Haar Cascades using OpenCV"""


Iface = gr.Interface(
    fn=detect_faces,
    inputs=[image, size_slider, neighbour_slider, scale_slider],
    outputs=out_im,
    #examples=[["data/9_Press_Conference_Press_Conference_9_86.jpg"], ["data/12_Group_Group_12_Group_Group_12_39.jpg"], ["data/31_Waiter_Waitress_Waiter_Waitress_31_55.jpg"]],
    title="Haar Cascade Object Detection",
).launch()