Home > Article > Technology peripherals > How to blur faces in real time using Python
Translator | Bugatti
Review | Chonglou
You might use face blur for several reasons. Hide faces in videos or images. Privacy and security concerns are the main reasons. Most video sharing platforms and video editing software have built-in face blur features.
You can create your own face blur program from scratch using Python, OpenCV and NumPy libraries.
To complete the study of this article, you need to be familiar with the basic knowledge of Python and have a basic understanding of the use of the NumPy library.
Open any Python IDE you are familiar with. Create a virtual environment to install the required libraries. Create a new Python file. Go to the terminal and run the following commands to install the required libraries. Pass the libraries as a space-separated list.
pip install OpenCV-python NumPy
You will use OpenCV to obtain and preprocess the video input and NumPy to process the array.
Once you have installed the library, wait for the IDE to update the project backbone. Once the updates are complete and your environment is ready, you can start coding.
Note: The complete source code can be found in the GitHub repository (https://github.com/makeuseofcode/Face-Blurring).
First, import the OpenCV library and NumPy library. This will enable you to call and use any function they support. Import OpenCV-python as cv2.
import cv2 import numpy as np
The OpenCV-python module uses the name cv2 as a convention established by the OpenCV community. OpenCV-Python is a Python wrapper for the OpenCV library, written in C.
Create a variable and initialize the VideoCapture object. If you want to use your computer's main camera as the input source, you should pass 0 as the parameter. To use an external camera connected to your computer, pass 1. To perform face blurring on a pre-recorded video, pass the path of the video instead. To use a remote camera, pass the camera's URL, which contains the IP address and port number.
cap = cv2.VideoCapture(0)
To perform face blurring on input, you need these three functions:
Create an input preprocessing function that takes each frame of the input video as its input. Initialize the CascadeClassifier class, which you will use to detect faces. Resize the frame to 640*640 pixels. Convert the resized frames to grayscale for processing, and finally detect faces in the input and bind them to rectangles.
def image_preprocess(frame): face_detector = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') resized_image = cv2.resize(frame, (640, 640)) gray_image = cv2.cvtColor(resized_image, cv2.COLOR_BGR2GRAY) face_rects = face_detector.detectMultiScale( gray_image, 1.04, 5, minSize=(20, 20)) return resized_image, face_rects
This function returns a tuple containing the resized image and a list of rectangles representing the detected faces.
Create a blur function to blur the input face. This function takes as input the resized frame and the list of rectangles surrounding the face returned by the preprocessing function. Loop through face rectangles. Calculate the center of each rectangle and the radius of the blur circle. Creates a black image with the same dimensions as the resized frame by initializing all pixels to 0. Using the calculated radius, draw a white circle on the black image centered on the face rectangle. Finally, it blurs the image on the white circle.
def face_blur(resized_frame, face_rects): for (x, y, w, h) in face_rects: # Specifying the center and radius # of the blurring circle center_x = x + w // 3 center_y = y + h // 3 radius = h // 1 # creating a black image having similar # dimensions as the frame mask = np.zeros((resized_frame.shape[:3]), np.uint8) # draw a white circle in the face region of the frame cv2.circle(mask, (center_x, center_y), radius, (255, 255, 255), -1) # blurring the whole frame blurred_image = cv2.medianBlur(resized_frame, 99) # reconstructing the frame: # - the pixels from the blurred frame if mask > 0 # - otherwise, take the pixels from the original frame resized_frame = np.where(mask > 0, blurred_image, resized_frame) return resized_frame
This function uses the NumPy where() function to reconstruct the frame during the blur process.
Create a main function to serve as the entry point of the program. It will then control the program flow. This function will start an infinite loop that continuously captures frames of the video input. Call the read method of the cap object to read frames from the camera.
The function then passes the frame to the preprocessing function and the return value to another function face_blur to obtain the blurred image. It then resizes the frame returned by the blur function and displays the output.
def main(): while True: success, frame = cap.read() resized_input, face_rects = image_preprocess(frame) blurred_image = face_blur(resized_input, face_rects) # Diplaying the blurred image cv2.imshow("Blurred image", cv2.resize(blurred_image, (500, 500))) if cv2.waitKey(1) == ord("q"): break
This function also terminates the output display when the user presses the q key.
Make sure to run the main function first when running the script. This condition will be false if the script is imported as a module in another program.
if __name__ == "__main__": main()
This allows you to use the script as a module or run it as a standalone program. When the program runs, you should see output similar to this:
The face has been blurred and cannot be recognized come out.
You can use face blur to protect privacy in many types of application environments. Street View and mapping services use blurring technology to obscure the faces of people in images. Law enforcement uses face blurring technology to protect the identities of witnesses.
Many video sharing platforms have also integrated face blur functions for users. Comparing the use of face blur in these areas can help you see how other platforms are integrating this technology.
Original link: https://www.makeuseof.com/python-blur-human-faces-real-time/
The above is the detailed content of How to blur faces in real time using Python. For more information, please follow other related articles on the PHP Chinese website!