import face_recognition import cv2 import gradio as gr from PIL import Image import numpy as np import torch import kornia as K from kornia.contrib import FaceDetector, FaceDetectorResult device = torch.device('cpu') face_detection = FaceDetector().to(device) def scale_image(img: np.ndarray, size: int) -> np.ndarray: h, w = img.shape[:2] scale = 1. * size / w return cv2.resize(img, (int(w * scale), int(h * scale))) def apply_blur_face(img: torch.Tensor, img_vis: np.ndarray, det: FaceDetectorResult): # crop the face x1, y1 = det.xmin.int(), det.ymin.int() x2, y2 = det.xmax.int(), det.ymax.int() roi = img[..., y1:y2, x1:x2] if roi.shape[-1]==0 or roi.shape[-2]==0: return # apply blurring and put back to the visualisation image roi = K.filters.gaussian_blur2d(roi, (21, 21), (100., 100.)) roi = K.color.rgb_to_bgr(roi) img_vis[y1:y2, x1:x2] = K.tensor_to_image(roi) def run(image): image.thumbnail((1280, 1280)) img_raw = np.array(image) # preprocess img = K.image_to_tensor(img_raw, keepdim=False).to(device) img = K.color.bgr_to_rgb(img.float()) with torch.no_grad(): dets = face_detection(img) dets = [FaceDetectorResult(o) for o in dets] img_vis = img_raw.copy() for b in dets: if b.score < 0.5: continue apply_blur_face(img, img_vis, b) return Image.fromarray(img_vis) content_image_input = gr.inputs.Image(label="Content Image", type="pil") description="Privacy first! Upload an image of a groupf of people and blur their faces automatically." article=""" Demo built on top of kornia and opencv, based on this example. """ examples = [["./images/family.jpeg"], ["./images/crowd.jpeg"], ["./images/crowd1.jpeg"]] app_interface = gr.Interface(fn=run, inputs=[content_image_input], outputs="image", title="Blurry Faces", description=description, examples=examples, article=article) app_interface.launch()