|
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, |
|
|
|
title="Haar Cascade Object Detection", |
|
).launch() |