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.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 = "

This is a Gradio demo for Kornia's Face Detection.

To use it, simply upload your image, or click one of the examples to load them

" article = "

Kornia Docs | Kornia Github Repo | Kornia Face Detection Tutorial

" examples = ['sample.jpg'] face = gr.Interface( detect, gr.inputs.Image(type="numpy"), gr.Image(type="pil", interactive=False), examples=examples, title=title, description=description, article=article, live=True, allow_flagging="never" ) face.launch()