Use Python and OpenCV to realize camera face detection and screenshot function
Overview
In modern applications, face detection is a very important technology and is widely used in security monitoring, identity verification and other fields. This article will introduce in detail how to use Python and OpenCV libraries to implement camera face detection and screenshots, and show the entire process through specific code examples.
Environmental preparation
Before you start writing your code, make sure that the OpenCV library is installed. You can install it using the following command:
pip install opencv-python
Detailed code explanation
# -*- coding: utf-8 -*- # import into openCV libraryimport cv2 import os import time # Call the camera to detect faces and take screenshotsdef camera(window_name, path_name): # Linux does not display the graphical interface (window_name) # Video source, from USB camera cap = (0) # Tell OpenCV to use the face recognition classifier classfier = (()+"/haarcascade_frontalface_alt.xml") # Recognize the color of the border to be drawn after the face is found. In RGB format, color is an array that cannot be added or deleted. color = (0, 255, 0) num = 0 while (): ok, frame = () # Read a frame of data if not ok: break # Convert the current frame image to a grayscale image grey = (frame, cv2.COLOR_BGR2GRAY) # Face detection, 1.2 and 2 are the picture scaling ratio and the number of valid points to be detected respectively faceRects = (grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32)) if len(faceRects) > 0: # If greater than 0, a face is detected for faceRect in faceRects: # Frame each face individually x, y, w, h = faceRect num = num + 1 # Save the current frame as an image img_name = "%s/%" % (path_name, num) image = frame[y - 10: y + h + 10, x - 10: x + w + 10] (img_name, image, [int(cv2.IMWRITE_PNG_COMPRESSION), 9]) # Delay 60s, don't send it too frequently, just know it's time to come # (60) # Draw a rectangular frame (frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2) # Show how many face pictures have been captured font = cv2.FONT_HERSHEY_SIMPLEX (frame, 'num:%d/1000' % (num), (x + 30, y + 30), font, 1, (255, 0, 255), 4) # Show the image and comment out the Linux (window_name, frame) c = (10) if c & 0xFF == ord('q'): break # Release the camera and destroy all windows () () if __name__ == '__main__': camera("watchdog", ()+"/face")
Code parsing
1. Import the necessary modules
# -*- coding: utf-8 -*- # import into openCV libraryimport cv2 import os import time
-
# -*- coding: utf-8 -*-
: Specify the file encoding as UTF-8. -
import cv2
: Import the OpenCV library for image processing and face detection. -
import os
: Import the os module for file path operation. -
import time
: Import time module for delayed operations.
2. Define camera function
def camera(window_name, path_name):
-
def camera(window_name, path_name):
: Define a namecamera
function, parameterwindow_name
It is the window name,path_name
It is the path to save the screenshot.
3. Create a window
# Linux does not display the graphical interface (window_name)
-
(window_name)
: Create a window to display the video stream. This line of code can be commented out under Linux to not display the graphical interface.
4. Turn on the camera
# Video source, from USB camera cap = (0)
-
(0)
: Turn on the default camera. Parameter 0 indicates the default camera.
5. Load the face recognition classifier
# Tell OpenCV to use the face recognition classifier classfier = (()+"/haarcascade_frontalface_alt.xml")
-
(...)
: Loading a pre-trained Haar cascade classifier for detecting faces. -
()+"/haarcascade_frontalface_alt.xml"
: Specify the path to the classifier file.
6. Set border color
# Recognize the color of the border to be drawn after the face is found. In RGB format, color is an array that cannot be added or deleted. color = (0, 255, 0)
-
color = (0, 255, 0)
: Define the border color to green.
7. Main loop
num = 0 while (): ok, frame = () # Read a frame of data if not ok: break # Convert the current frame image to a grayscale image grey = (frame, cv2.COLOR_BGR2GRAY) # Face detection, 1.2 and 2 are the picture scaling ratio and the number of valid points to be detected respectively faceRects = (grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32)) if len(faceRects) > 0: # If greater than 0, a face is detected for faceRect in faceRects: # Frame each face individually x, y, w, h = faceRect num = num + 1 # Save the current frame as an image img_name = "%s/%" % (path_name, num) image = frame[y - 10: y + h + 10, x - 10: x + w + 10] (img_name, image, [int(cv2.IMWRITE_PNG_COMPRESSION), 9]) # Delay 60s, don't send it too frequently, just know it's time to come # (60) # Draw a rectangular frame (frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2) # Show how many face pictures have been captured font = cv2.FONT_HERSHEY_SIMPLEX (frame, 'num:%d/1000' % (num), (x + 30, y + 30), font, 1, (255, 0, 255), 4) # Show the image and comment out the Linux (window_name, frame) c = (10) if c & 0xFF == ord('q'): break
-
num = 0
: Initialize the counter. -
while ():
: Enter an infinite loop and read the camera image in real time. -
ok, frame = ()
: Read a frame of image from the camera. -
if not ok:
: Check whether the read is successful, and exit the loop if it fails. -
grey = (frame, cv2.COLOR_BGR2GRAY)
: Convert the image to a grayscale image. -
faceRects = (grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))
: Detect faces in the image. -
if len(faceRects) > 0:
: Check whether the face is detected. -
for faceRect in faceRects:
: Iterate through each face detected. -
x, y, w, h = faceRect
: Get the position and size of the face. -
num = num + 1
: Increase the counter. -
img_name = "%s/%" % (path_name, num)
: Generate the file name that saves the image. -
image = frame[y - 10: y + h + 10, x - 10: x + w + 10]
: Crop the face area and expand the boundaries. -
(img_name, image, [int(cv2.IMWRITE_PNG_COMPRESSION), 9])
: Save the image. -
(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2)
: Draw a rectangular box on the image. -
font = cv2.FONT_HERSHEY_SIMPLEX
: Set the font style. -
(frame, 'num:%d/1000' % (num), (x + 30, y + 30), font, 1, (255, 0, 255), 4)
: Displays the currently captured face number on the image. -
(window_name, frame)
: Displays an image with rectangular marks. -
c = (10)
: Wait for 10 milliseconds, wait for the user to press the key. -
if c & 0xFF == ord('q'):
: Press the ‘q’ key to exit the loop.
8. Free up resources
# Release the camera and destroy all windows () ()
-
()
: Release camera resources. -
()
: Close all OpenCV windows.
9. Main program entry
if __name__ == '__main__': camera("watchdog", ()+"/face")
-
if __name__ == '__main__':
: Check whether this script is run directly. -
camera("watchdog", ()+"/face")
: Calledcamera
Function, pass in window name and path to save screenshots.
Complete code
# -*- coding: utf-8 -*- # import into openCV libraryimport cv2 import os import time # Call the camera to detect faces and take screenshotsdef camera(window_name, path_name): # Linux does not display the graphical interface (window_name) # Video source, from USB camera cap = (0) # Tell OpenCV to use the face recognition classifier classfier = (()+"/haarcascade_frontalface_alt.xml") # Recognize the color of the border to be drawn after the face is found. In RGB format, color is an array that cannot be added or deleted. color = (0, 255, 0) num = 0 while (): ok, frame = () # Read a frame of data if not ok: break # Convert the current frame image to a grayscale image grey = (frame, cv2.COLOR_BGR2GRAY) # Face detection, 1.2 and 2 are the picture scaling ratio and the number of valid points to be detected respectively faceRects = (grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32)) if len(faceRects) > 0: # If greater than 0, a face is detected for faceRect in faceRects: # Frame each face individually x, y, w, h = faceRect num = num+1 # Save the current frame as an image img_name = "%s/%" % (path_name, num) image = frame[y - 10: y + h + 10, x - 10: x + w + 10] (img_name, image, [int(cv2.IMWRITE_PNG_COMPRESSION), 9]) # Delay 60s, don't send it too frequently, just know it's time to come # (60) # Draw a rectangular frame (frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2) # Show how many face pictures have been captured font = cv2.FONT_HERSHEY_SIMPLEX (frame, 'num:%d/1000' % (num), (x + 30, y + 30), font, 1, (255, 0, 255), 4) # Show the image and comment out the Linux (window_name, frame) c = (10) if c & 0xFF == ord('q'): break # Release the camera and destroy all windows () () if __name__ == '__main__': camera("watchdog", ()+"/face")
test
- Make sure your camera is working properly.
- Run the script:
python3 face_detection.py
- Once the camera is turned on, you will see a window showing the live video stream and a green rectangle is drawn around the detected face.
- Press the ‘q’ key to exit the program.
Summarize
This article details how to use Python and OpenCV libraries to implement camera face detection and screenshots, and shows the entire process through specific code examples. By usingTurn on the camera,
Load the pretrained Haar cascade classifier,
Convert image color space,
Draw a rectangle,
Saving images ultimately realizes the function of detecting and saving face images in real-time video streams.
This is the article about using Python and OpenCV to implement face detection and screenshots for cameras. For more related Python OpenCV face detection content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!
Related Articles
Python HTMLTestRunner test report view button failure solution
This article mainly introduces the Python HTMLTestRunner test report view button failure solution. The example code in the article is introduced in very detailed, which has certain reference value for everyone's learning or work. Friends who need it can refer to it.2020-05-05Detailed explanation of the processing operations on Excel in Python
Excel is a common spreadsheet file format, widely used in data recording and processing. Python provides multiple third-party libraries that can easily operate Excel. Let me talk about it in detail below.2023-07-07Python uses VIF to detect multicollinearity
Multicollinearity refers to two or more independent variables in the multivariate regression model, which have a high correlation. This article mainly introduces how to use VIF to detect multicollinearity. If you need it, please refer to it.2023-12-12Example analysis of Simpson method for python realizing numerical integral
This article mainly introduces the Simpson method of python to implement numerical integrals, and analyzes the relevant skills of Python to implement integral operations. Friends who need it can refer to it.2015-06-06Detailed explanation of simple queues and cross-process lock instances implemented by python based on mysql
This article mainly introduces the simple queue and cross-process lock implemented by Python based on mysql. Friends who need it can refer to it.2014-07-07The third basic tutorial on openingCV learning
pencv is a tool used to quickly handle image processing and computer vision problems. It supports development of multiple languages such as C++, python, java, etc. The following article mainly introduces relevant materials about the basic tutorial on the introduction to openCV. Friends who need it can refer to it.2022-11-11How to automatically upload a liked number in python selenium
This article mainly introduces the operation code for automatically uploading Youzan order numbers in Python selenium. The code is simple and easy to understand, very good, and has certain reference value. Friends who need it can refer to it.2018-07-07Example of Python crawler crawling proxy IP and verifying availability
Today, the editor will share with you an example of Python crawler crawling proxy IP and verifying availability. It has good reference value and hope it will be helpful to everyone. Let's take a look with the editor2018-05-05Example explanation of Python implementing automatic screenshot of web pages
Today, the editor will share with you an example explanation of Python's automatic screenshot of web pages. It has good reference value and hope it will be helpful to everyone. Let's take a look with the editor2018-05-05Python automatic 12306 ticket grabbing software implementation code
This article mainly introduces the implementation code of Python automatic 12306 ticket grabbing software in detail, which has certain reference value. Interested friends can refer to it.2018-02-02