How to Blur Faces in Images Using OpenCV in Python?

Posted in /  

How to Blur Faces in Images Using OpenCV in Python?
vinaykhatri

Vinay Khatri
Last updated on December 22, 2024

    Python is one of the most popular programming languages for machine learning and image processing. With the OpenCV library, we can process images and videos using Python. Detecting faces in an image and blurring it is one of the most common applications of image and video processing with machine learning, and with Python and OpenCV, we can detect faces and blur them by writing only a few lines of code. In this tutorial, we will walk you through a Python tutorial on how to blur faces in images using OpenCV in Python. Also, at the end of the tutorial, we will write a Python program to blur faces for live webcam video, but before advancing to the Python code, let's first download and install all the dependencies.

    Install Dependencies

    1) Python OpenCV Library

    As discussed before, we will be using the OpenCV library for this Python tutorial. This Python tutorial will still work even if you have an older version of Python on your system. However, it will be good if you have the latest Python version installed on your system. Having the latest version of Python will ensure that you don't run into any issues while running the code. Now for this tutorial, you need to install the OpenCV library, and you can simply install it using the following pip installation command:

    pip install opencv-python

    2) Download the Harr Cascade haarcascade_frontalface_default.xml

    Blurring faces in an image is divided into two steps:

    1. Detecting the coordinates for the faces, and
    2. Blurring those coordinates.

    Detecting faces in an image is an application of machine learning. Thus, it can be done with the help of classifiers. Luckily, OpenCV supports the most common Haar Cascade classifiers to detect faces in an image. A classifier needs to be trained on thousands of data sets, and for this tutorial, you can copy and paste the trained haarcascade_frontalface_default.xml classifier and save it as harr_face_detect_classifier.xml . We have also written a tutorial on how to detect faces with OpenCV , and we will be using that source code to detect faces in the images. We will suggest you go through that article first if you want to learn how to detect faces in OpenCV. If you don't want to do so, it's ok as we have covered all of that and blurring the image in this tutorial too.

    3) The Image

    For this tutorial on blurring faces in an image, we will be using the following "Father-Daughter.jpg." We are all set now. Proceed with opening your best Python IDE or text editor and start coding.

    How to Blur Faces in Images Using OpenCV in Python?

    We will start by importing the Python OpenCV module and loading the Father-Daughter.jp image.

    import cv2 as cv
    
    #load image
    image = cv.imread("Father-Daughter.jpg")

    The cv.imread() function loads the image and returns a Numpy ndarray of 3 channels representing the BGR matrix. By default, OpenCV reads the image in BGR (Blue Green Red) format. After reading (or loading) the image, we will convert it into a GrayScale image because it's always a good practice to convert a BGR image to a grayscale image to reduce the color intensity noises. The Haar Cascade Face detection classifier does not care about face color intensity. It simply detects the faces. Therefore, converting a BGR image to its GrayScale equivalent would not affect the classifier.

    #convert the BGR image to a grayscale image
    gray_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

    The cv.cvtColor() function accepts two parameters, the image and the color conversion code. Here, we want to convert our BGR image to a GrayScale image, and that's why we specify the cv.COLOR_BGR2GRAY conversion code. Now, we need to initialize the object for the trained Haar Cascade classifier haarcascade_frontalface_default.xml that we have copied, pasted, and saved in our local system as harr_face_detect_classifier.xml .

    #read the harr_face_detect_classifier.xml
    harr_cascade = cv.CascadeClassifier("harr_face_detect_classifier.xml")

    The cv.CascadeClassifier() method will initialize the trained Harr Cascade classifier, and now we can detect faces in the GrayScale image using the Harr Cascade detectMultiScale() method.

    face_cords = harr_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=1)
    

    The detectMultiScale() method returns an array of detected face coordinates, and we can loop through the face_cords coordinates and blur that area in the image.

    for x, y, w, h in face_cords:
        blur_face = image[y:y+h, x:x+w]
        blur_face = cv.GaussianBlur(blur_face,(23, 23), 30)
        image[y:y+blur_face.shape[0], x:x+blur_face.shape[1]] = blur_face

    First, we get a specific area of the face by image[y:y+h, x:x+w] , then blur that face area, and put that blurred area to the real image using the image[y:y+blur_face.shape[0], x:x+blur_face.shape[1]] = blur_face statement. Now, show the image using the cv.imshow() function.

    #show image
    cv.imshow("Blur Faces", image)
    cv.waitKey(0)

    Now put all the code together and execute. #Python Program to Blur Faces in Images Using OpenCV

    import cv2 as cv
    
    #load image
    image = cv.imread("Father-Daughter.jpg")
    
    #convert image to grayscale image
    gray_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    
    #read the harr_face_detect_classifier.xml
    harr_cascade = cv.CascadeClassifier("harr_face_detect_classifier.xml")
    
    face_cords = harr_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=1 )
    print(face_cords)
    for x, y, w, h in face_cords:
        blur_face = image[y:y+h, x:x+w]
        blur_face = cv.GaussianBlur(blur_face,(23, 23), 30)
        image[y:y+blur_face.shape[0], x:x+blur_face.shape[1]] = blur_face
    
    #show image
    cv.imshow("Blur Faces", image)
    cv.waitKey(0)

    Output

    Blur Faces in Videos with OpenCV in Python

    Now you know how to blur faces in images using OpenCV in Python. Next, let's write a Python script that can blur faces in videos and live streams. Blurring faces in a video are similar to blurring faces in an image. We can treat a video as a continuous frame of images and blur faces by detecting faces in every frame. Next, let's code to blur faces in a video with OpenCV in Python.

    import cv2 as cv
    
    #start web cam
    capture = cv.VideoCapture(0) # 0 for web-cam
    
    #read the harr_face_detect_classifier.xml
    harr_cascade = cv.CascadeClassifier("harr_face_detect_classifier.xml")
    
    while True:
        #read video frame by frame
        isTrue, frame= capture.read()
    
        gray_frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    
        face_cords = harr_cascade.detectMultiScale(gray_frame, scaleFactor=1.1, minNeighbors=1)
    
        #blur over faces
        for x, y, w, h in face_cords:
            blur_face = frame[y:y+h, x:x+w]
            blur_face = cv.GaussianBlur(blur_face,(23, 23), 30)
            frame[y:y+blur_face.shape[0], x:x+blur_face.shape[1]] = blur_face
    
        #show blur face Video
        cv.imshow("Blur Faces", frame)
    
        #press e to exit
        if cv.waitKey(20) ==ord("e"):
            break
    capture.release()
    capture.destroyAllWindows()
    

    Conclusion

    In this Python tutorial, we learned how to blur faces in images using OpenCV in Python. Moreover, we also learned to blur faces in videos and live video streams. For this tutorial, we have used the OpenCV GaussianBlur() method to blur the faces. Other than it, OpenCV also supports other blurring methods such as averaging. The blurring of faces in images and videos is divided into two steps, detecting faces and blurring faces. For this tutorial, we have used the straightforward and basic face detecting classifier, the Harr Cascade Classifier. People are also reading:

    Leave a Comment on this Post

    0 Comments