Home > Technology peripherals > AI > How to blur faces in real time using Python

How to blur faces in real time using Python

WBOY
Release: 2023-04-07 16:43:14
forward
1060 people have browsed it

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.

1. Establishing the environment

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
Copy after login

You will use OpenCV to obtain and preprocess the video input and NumPy to process the array.

How to blur faces in real time using Python

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).

2. Import the required libraries

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
Copy after login

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.

3. Get input

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)
Copy after login

To perform face blurring on input, you need these three functions:

  • Functions that preprocess the input.
  • Function that will blur the faces in the input.
  • The main function that will control the program flow and display the output.

4. Video input preprocessing

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
Copy after login

This function returns a tuple containing the resized image and a list of rectangles representing the detected faces.

5. Blur the face

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
Copy after login

This function uses the NumPy where() function to reconstruct the frame during the blur process.

6. Control the program flow

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
Copy after login

This function also terminates the output display when the user presses the q key.

7. Run the program

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()
Copy after login

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:

How to blur faces in real time using Python

The face has been blurred and cannot be recognized come out.

8. Practical applications of face blur

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!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template