File size: 2,244 Bytes
2cc56c8
30cf04a
2cc56c8
 
 
f61f295
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2cc56c8
 
 
f61f295
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2cc56c8
f61f295
2cc56c8
 
 
 
 
f61f295
 
2cc56c8
f61f295
2cc56c8
 
 
 
 
 
 
 
 
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
66
67
68
69
70
71
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 
<a href='https://github.com/kornia/kornia/blob/master/examples/face_detection/main.py' target='_blank'>this</a> 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()