%%capture
!pip install kornia
!pip install kornia-rs
Face Detection and blurring
Intermediate
Face detection
Blur
kornia.contrib
In this tutorial we will show how to use the Kornia Face Detection and how we can blurring these detected faces.
import io
import requests
def download_image(url: str, filename: str = "") -> str:
= url.split("/")[-1] if len(filename) == 0 else filename
filename # Download
= io.BytesIO(requests.get(url).content)
bytesio # Save file
with open(filename, "wb") as outfile:
outfile.write(bytesio.getbuffer())
return filename
= "https://raw.githubusercontent.com/kornia/data/main/crowd.jpg"
url download_image(url)
Import the needed libraries
import cv2
import kornia as K
import matplotlib.pyplot as plt
import numpy as np
import torch
from kornia.contrib import FaceDetector, FaceDetectorResult
# select the device and type
= torch.device("cpu") # use 'cuda:0'
device = torch.float32 dtype
Read the image with kornia
# load the image (face detector expects a image in rage 0-255 (8 bits))
= K.io.load_image("crowd.jpg", K.io.ImageLoadType.RGB8, device=device)[None, ...].to(dtype=dtype) # BxCxHxW
img = K.tensor_to_image(img.byte()) # to later visualize img_vis
=(8, 8))
plt.figure(figsize
plt.imshow(img_vis)"off")
plt.axis( plt.show()
Create the FaceDetector object and apply to the image
# create the detector and find the faces !
= FaceDetector().to(device, dtype)
face_detection
with torch.no_grad():
= face_detection(img)
dets
# to decode later the detections
= [FaceDetectorResult(o) for o in dets] dets
Create a function to crop the faces from the original image and apply blurring using the gaussian_blurd2d operator.
Alternatively, explore other blur operator in kornia.filters
.
# blurring paramters
int = 21 # kernel_size
k: float = 35.0 # sigma
s:
def apply_blur_face(img: torch.Tensor, img_vis: np.ndarray, x1, y1, x2, y2):
# crop the face
= img[..., y1:y2, x1:x2]
roi
# apply blurring and put back to the visualisation image
= K.filters.gaussian_blur2d(roi, (k, k), (s, s))
roi = K.tensor_to_image(roi) img_vis[y1:y2, x1:x2]
Let draw the detections and save/visualize the image
for b in dets:
# draw face bounding box around each detected face
= b.top_left.int().tolist()
top_left = b.bottom_right.int().tolist()
bottom_right = b.score.tolist()
scores
for score, tp, br in zip(scores, top_left, bottom_right):
= tp
x1, y1 = br
x2, y2
if score < 0.7:
continue # skip detection with low score
= cv2.rectangle(img_vis, (x1, y1), (x2, y2), (0, 255, 0), 2)
img_vis
# blur the detected faces
apply_blur_face(img, img_vis, x1, y1, x2, y2)
=(8, 8))
plt.figure(figsize
plt.imshow(img_vis)"off")
plt.axis( plt.show()
Play with the Real Time Demo
You can achieve 60 FPS in CPU using a standard WebCam.
See: https://github.com/kornia/kornia/blob/master/examples/face_detection/main_video.py
from IPython.display import YouTubeVideo
"hzQroGp5FSQ") YouTubeVideo(