Spaces:
Build error
Build error
File size: 1,645 Bytes
f61f295 |
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 |
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
import time
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]
#print(roi.shape)
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)
if __name__ == "__main__":
start = time.time()
for _ in range(100):
image = Image.open("./images/crowd.jpeg")
_ = run(image)
print('It took', (time.time()-start)/100, 'seconds.') |