Open in Colab

Face Detection and blurring#

In this tutorials we will show how to use

!pip install git+
!wget -O image.jpg

Import the needed libraries

import cv2
import numpy as np
import matplotlib.pyplot as plt

import torch
import kornia as K
from kornia.contrib import FaceDetector, FaceDetectorResult

# select the device and type
device = torch.device('cpu')  # use 'cuda:0'
dtype = torch.float32
/home/docs/checkouts/ TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See
  from .autonotebook import tqdm as notebook_tqdm

Read the image and convert to a torch.Tensor

# load the image and scale (if needed)
img_raw = cv2.imread('image.jpg', cv2.IMREAD_COLOR)

# preprocess
img = K.image_to_tensor(img_raw, keepdim=False).to(device, dtype)
img = K.color.bgr_to_rgb(img)

img_vis = K.tensor_to_image(img.byte().clone())  # to later visualise
plt.figure(figsize=(8, 8))
(-0.5, 1199.5, 1199.5, -0.5)

Create the FaceDetector object and apply to the image

# create the detector and find the faces !
face_detection = FaceDetector().to(device, dtype)

with torch.no_grad():
    dets = face_detection(img)

# to decode later the detections
dets = [FaceDetectorResult(o) for o in dets]
Downloading: "" to /home/docs/.cache/torch/hub/checkpoints/yunet_final.pth
  0%|          | 0.00/396k [00:00<?, ?B/s]
100%|██████████| 396k/396k [00:00<00:00, 11.3MB/s]

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
k: int = 21     # kernel_size
s: float = 35.  # sigma

def apply_blur_face(img: torch.Tensor, img_vis: np.ndarray, det: FaceDetectorResult):
    # crop the face
    x1, y1 =,
    x2, y2 =,
    roi = img[..., y1:y2, x1:x2]

    # apply blurring and put back to the visualisation image
    roi = K.filters.gaussian_blur2d(roi, (k, k), (s, s))
    roi = K.color.rgb_to_bgr(roi)
    img_vis[y1:y2, x1:x2] = K.tensor_to_image(roi)

Let draw the detections and save/visualize the image

for b in dets:
    if b.score < 0.6:  # skip detections with lower score
    # draw face bounding box around each detected face
    x1, y1 =
    x2, y2 =
    img_vis = cv2.rectangle(img_vis, (x1, y1), (x2, y2), (0, 255, 0), 4)

    # blur the detected faces
    apply_blur_face(img, img_vis, b)

plt.figure(figsize=(8, 8))

# save and show image
cv2.imwrite('img_out.jpg', img_vis)

Play with the Real Time Demo#

You can achieve 60 FPS in CPU using a standard WebCam.


from IPython.display import YouTubeVideo