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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
