Detect the face from live video Stream and blur the face Using OpenCV

Ankit Shukla
2 min readJul 30, 2023

--

Greetings and best wishes for an insightful read😇 ,

Hope this blog finds you great and healthy !!😊

Lets begin with brief introduction about me…..

Hi, This is Ankit Shukla and In this article we will discuss about How to detect and blur the human face.

What is OpenCV ?

OpenCV is a great tool for image processing and performing computer vision tasks. It is an open-source library that can be used to perform tasks like face detection, objection tracking, landmark detection, and much more.

How to Install Open Cv2?

Firstly, open the Command prompt and install the python opencv library using given below command

pip install opencv-python

https://www.geeksforgeeks.org/how-to-install-opencv-for-python-in-windows/

After the installation, we use Haar cascade Classifier

What is the Haar Cascade Classifier?

Haar Cascade Classifier is an Object Detection Algorithm used to identify faces in an image or a real-time video.

Face Detection with Haar Cascade Classifier

OpenCV uses Haar Feature-based Cascade Classifiers and comes with pre-trained XML files of various Haar Cascades. and Face detection with Haar Cascades algorithm needs a lot of positive images and negative images to train the classifier. The model created from this training is available in the OpenCV GitHub repository

https://github.com/opencv/opencv/tree/master/data/haarcascades.

below are the code used to detect and blur :-

Importing the CV2 Library

import cv2

Set up the video source to the default webcam, which OpenCV can easily capture. Here we are using the External Camera, so we give the Argument ‘1’

capture=cv2.VideoCapture(1)

Import the HaarCascade Classifier :

model = cv2.CascadeClassifier(“haarcascade_frontalface_default.xml”)

we will use the detectMultiScale() function to detect the
faces from the video stream.

Adjust coordinates accordingly

while True:
ret, img = cap.read()
face_detect = model.detectMultiScale(img)
if len(face_detect) == 0:
print("No face Found")
else:
x1 = face_detect[0][0]
y1 = face_detect[0][1]
x2 = face_detect[0][2] + x1
y2 = face_detect[0][3] + y1
capimg = img[y1:y2 , x1:x2]
bluring_img = cv2.blur(capimg, (50,50))
Frame_img = cv2.rectangle(img, (x1,y1), (x2,y2), [0,255,0],2)
img[y1:y2 , x1:x2] = bluring_img

cv2.imshow("blurred face detected",img)
cv2.imshow("Frame set on Image",rect_img)
if cv2.waitKey(100) == 13:
breakcv2.destroyAllWindows()

Thanks for reading !!

--

--

Ankit Shukla
Ankit Shukla

Written by Ankit Shukla

| Software Developer | SDET |

No responses yet