File size: 2,608 Bytes
9e40f68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05c65ac
9e40f68
 
 
 
 
 
 
 
 
 
 
9890dda
9e40f68
9890dda
 
 
 
 
 
9e40f68
 
 
 
 
 
 
05c65ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import cv2
import numpy as np
import torch
import kornia as K
from kornia.core import Tensor
from kornia.contrib import FaceDetector, FaceDetectorResult, FaceKeypoint

def draw_keypoint(img: np.ndarray, det: FaceDetectorResult, kpt_type: FaceKeypoint) -> np.ndarray:
    kpt = det.get_keypoint(kpt_type).int().tolist()
    return cv2.circle(img, kpt, 2, (255, 0, 0), 2)

def detect(img_raw):
    # preprocess
    if img_raw is not None and len(img_raw.shape) == 3:
        img = K.utils.image_to_tensor(img_raw, keepdim=False)
        img = K.color.bgr_to_rgb(img.float())
        # create the detector and find the faces !
        face_detection = FaceDetector()
        with torch.no_grad():
            dets = face_detection(img)
        dets = [FaceDetectorResult(o) for o in dets[0]]
        img_vis = img_raw.copy()
        vis_threshold = 0.8
        for b in dets:
            if b.score < vis_threshold:
                continue
            # Draw face bounding box
            img_vis = cv2.rectangle(img_vis, b.top_left.int().tolist(), b.bottom_right.int().tolist(), (0, 255, 0), 4)
            # Draw Keypoints
            img_vis = draw_keypoint(img_vis, b, FaceKeypoint.EYE_LEFT)
            img_vis = draw_keypoint(img_vis, b, FaceKeypoint.EYE_RIGHT)
            img_vis = draw_keypoint(img_vis, b, FaceKeypoint.NOSE)
            img_vis = draw_keypoint(img_vis, b, FaceKeypoint.MOUTH_LEFT)
            img_vis = draw_keypoint(img_vis, b, FaceKeypoint.MOUTH_RIGHT)
        return img_vis

title = "Kornia Face Detection"
description = "<p style='text-align: center'>This is a Gradio demo for Kornia's Face Detection.</p><p style='text-align: center'>To use it, simply upload your image, or click one of the examples to load them</p>"
article = "<p style='text-align: center'><a href='https://kornia.readthedocs.io/en/latest/' target='_blank'>Kornia Docs</a> | <a href='https://github.com/kornia/kornia' target='_blank'>Kornia Github Repo</a> | <a href='https://kornia.readthedocs.io/en/latest/applications/face_detection.html' target='_blank'>Kornia Face Detection Tutorial</a></p>"
examples = ['sample.jpg']

with gr.Blocks(title=title) as demo:
    gr.Markdown(f"# {title}")
    gr.Markdown(description)
    
    with gr.Row():
        input_image = gr.Image(type="numpy", label="Input Image")
        output_image = gr.Image(type="numpy", label="Detected Faces")
    
    gr.Examples(examples, inputs=input_image)
    
    input_image.change(fn=detect, inputs=input_image, outputs=output_image)
    
    gr.Markdown(article)

if __name__ == "__main__":
    demo.launch()