Blur the face in an image or video

Published

May 24, 2022

Blurring the face area of people from videos is done in all news channels and to hide the identity of a person. With computer vision, We can automatically detect the face region of the person and use it to blur the image. In this project we will build a computer vision model which can detect face in an image and blur it.

1. Read an image
2. Convert it to grayscale
3. load Cascade Classifier
4. Detect Faces
5. Draw Bounding Box
6. Blur the face
Code
# Import necessary library
import cv2
import matplotlib.pyplot as plt

Step-1: Read an image

Code
img = cv2.imread('../images/face.jpg')
plt.imshow(img[:,:,::-1]) # opencv read an image into BGR mode, to convert it into RGB we reverse the image array

Step-2: Convert the image to grayscale

Code
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.imshow(gray, cmap='gray')

Step-3: Loading OpenCV CascadeClassifier

Code
face_classifier = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml')

Step-4: Detecting faces in the grayscaled image

Code
faces = face_classifier.detectMultiScale(gray)

Step-5: Draw Blounding Box around the detected faces

Code
for (x,y,w,h) in faces:
    cv2.rectangle(img, (x,y), (x+w,y+h), (127,0,255),2)
    plt.imshow(img[:,:,::-1])

Step-6: Blur the face

Code
# select region of face in the original image
ROI = img[y:y+h, x:x+w]

# blur the face region
blur_face = cv2.GaussianBlur(ROI, (91,91),0)
Code
# replace original face with the blurred one
img[y:y+h, x:x+w] = blur_face
Code
# Final Image
plt.imshow(img[:,:,::-1])