current position：Home>Blurring and anonymizing faces using OpenCV and python
Blurring and anonymizing faces using OpenCV and python
2022-01-31 02:51:53 【Haiyong】
「 This is my participation 11 The fourth of the yuegengwen challenge 4 God , Check out the activity details ：2021 One last more challenge 」
Author URI ： Hai Yong
Author's brief introduction ：HDZ Core group members 、 High quality creators in the whole stack field 、 Reelection C Standing in the top ten of the weekly list
Fan benefits ： Into the Fans group Send four books a week （ Everyone has ）, Send all kinds of small gifts every month ( Nuggets enamel cup 、 Pillow 、 Mouse pad 、 Mugs, etc )
In this paper , We will learn how to use OpenCV and Python Blur and anonymize faces .
So , We will use cascaded classifiers to detect faces . Make sure to download the same from this link xml file ：
- First , We use the built-in face detection algorithm , Face detection from real-time video or image . ad locum , We will use a cascaded classifier method to extract data from real-time video （ Use a webcam ） Face detection in .
- then , Read frames from real-time video . Store the latest frame and convert it to grayscale , To better understand the characteristics .
- Now? , In order to make the output beautiful , We will make a color border rectangle around the detected face . however , We want the detected face to be blurred , So we use the median fuzzy function to do the same thing , And mention the area where the face should be blurred .
- and , Now we want to show the blurred face , Use imshow The frame read by the function , We want it to be shown , Until we press a key .
Step by step implementation ：
step 1： Import face detection algorithm , It is called cascade classifier .
import cv2 # Face detection cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") Copy code
step 2： Capture frames from video , To detect faces from frames
video_capture = cv2.VideoCapture(0) while True: # Capture the latest frame from the video check, frame = video_capture.read() Copy code
step 3： Change the captured frame to grayscale .
# Convert frames to grayscale （ Black and white shadows ） gray_image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face = cascade.detectMultiScale(gray_image, scaleFactor=2.0, minNeighbors=4) Copy code
step 4： Draw a color rectangle around the detected face .
for x, y, w, h in face: # Draw a border around the detected face # （ The border color here is green , The thickness is 3） image = cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 3) Copy code
step 5： Blur the part inside the rectangle （ Contains the detected face ）.
# Blur the face in the rectangle image[y:y+h, x:x+w] = cv2.medianBlur(image[y:y+h, x:x+w], 35) Copy code
step 6： Show final output , That is, the detected face （ In rectangle ） It's fuzzy .
# Show blurred faces in the video cv2.imshow('face blurred', frame) key = cv2.waitKey(1) Copy code
Here is the complete implementation ：
import cv2 # Face detection cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") # VideoCapture It's a function , Used to capture video from cameras connected to the system # You can pass on 0 or 1 # 0 For laptop webcam # 1 For external webcam video_capture = cv2.VideoCapture(0) # One while Loop runs infinite times , Capture an unlimited number of frames for video , Because video is a combination of frames while True: # Capture the latest frame from the video check, frame = video_capture.read() # Convert frames to grayscale （ Black and white shadows ） gray_image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Multiple faces are detected in the captured frame # scaleFactor： Parameter specifies how much the image size is reduced at each image scale . # minNeighbors: Parameter specifies how many neighbors each rectangle should have to keep it . # The rectangle contains the detection object . # The object here is the face . face = cascade.detectMultiScale( gray_image, scaleFactor=2.0, minNeighbors=4) for x, y, w, h in face: # Draw a border around the detected face . #（ The border color here is green , The thickness is 3） image = cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 3) # Blur the face in the rectangle image[y:y+h, x:x+w] = cv2.medianBlur(image[y:y+h, x:x+w], 35) # Show blurred faces in the video cv2.imshow('face blurred', frame) key = cv2.waitKey(1) # This statement runs only once per frame . # Basically , If we get a key , And that key is a q if key == ord('q'): break # We will pause and exit while loop , # And then run ： video_capture.release() cv2.destroyAllWindows() Copy code
Write in the last
I've been writing a technology blog for a long time , And mainly through the Nuggets , This is one of my articles OpenCV and Python Blur and anonymize faces . I like to share technology and happiness through articles . You can visit my blog ： juejin.cn/user/204034… To learn more . I hope you will like ！
You are welcome to put forward your opinions and suggestions in the comment area ！
author[Haiyong],Please bring the original link to reprint, thank you.
The sidebar is recommended
- [Python from introduction to mastery] (V) Python's built-in data types - sequences and strings. They have no girlfriend, not a nanny, and can only be used as dry goods
- Does Python have a, = operator?
- Go through the string common sense in Python
- Fanwai 4 Handling of mouse events and solutions to common problems in Python opencv
- Summary of common functions for processing strings in Python
- When writing Python scripts, be sure to add this
- Python web crawler - Fundamentals (1)
- Pandas handles duplicate values
- Python notes (23): regular module
- Python crawlers are slow? Concurrent programming to understand it
guess what you like
Parameter passing of Python function
Stroke tuple in Python
Talk about ordinary functions and higher-order functions in Python
[Python data acquisition] page image crawling and saving
[Python data collection] selenium automated test framework
Talk about function passing and other supplements in Python
Python programming simulation poker game
leetcode 160. Intersection of Two Linked Lists （python）
Python crawler actual combat, requests module, python to grab the beautiful wallpaper of a station
Fanwai 5 Detailed description of slider in Python opencv and solutions to common problems
- My friend's stock suffered a terrible loss. When I was angry, I crawled the latest data of securities with Python
- Python interface automation testing framework -- if you want to do well, you must first sharpen its tools
- Python multi thread crawling weather website pictures and saving
- How to convert pandas data to excel file
- Python series tutorials 122
- Python Complete Guide - printing data using pyspark
- Python Complete Guide -- tuple conversion array
- Stroke the list in python (top)
- Analysis of Python requests module
- Comments and variables in Python
- New statement match, the new version of Python is finally going to introduce switch case?
- Fanwai 6 Different operations for image details in Python opencv
- Python crawler native code learning (I)
- Python quantitative data warehouse building series 2: Python operation database
- Python code reading (Part 50): taking elements from list intervals
- Pyechart + pandas made word cloud pictures of 19 report documents
- [Python crawler] multithreaded daemon & join() blocking
- Python crawls cat pictures in batches to realize thousand image imaging
- Van * Python | simple crawling of a planet
- Input and output of Python practice
- Django ORM details - fields, attributes, operations
- Python web crawler - crawling cloud music review (3)
- Stroke list in python (bottom)
- What cat is the most popular? Python crawls the whole network of cat pictures. Which one is your favorite
- [algorithm learning] LCP 06 Take coins (Java / C / C + + / Python / go / trust)
- Python shows the progress of downloading files from requests
- Solve the problem that Django celery beat prompts that the database is incorrectly configured and does not support multiple databases
- Bamboolib: this will be one of the most useful Python libraries you've ever seen
- Python quantitative data warehouse construction 3: data drop library code encapsulation
- The source code and implementation of Django CSRF Middleware
- Python hashlib module
- The cover of Python 3 web crawler development (Second Edition) has been determined!
- The introduction method of executing Python source code or Python source code file (novice, please enter the old bird and turn left)
- [Python basics] explain Python basic functions in detail, including teaching and learning
- Python web crawler - crawling cloud music review (4)
- The first step of scientific research: create Python virtual environment on Linux server
- Writing nmap scanning tool in Python -- multithreaded version
- leetcode 2057. Smallest Index With Equal Value（python）
- Bamboolib: this will be one of the most useful Python libraries you've ever seen
- Python crawler actual combat, requests module, python realizes capturing a video barrage