Python - OpenCV implements camera face recognition (pro-test version)

To do webcam face recognition with Python 3 and OpenCV, you can follow these steps:

0. Install OpenCV software

Go to the official website to download and install directly. If you use OpenCV in C++, you need to compile the source code and configure environment variables.

1. Install the OpenCV library

Enter the following command at the command line:

pip install opencv-python

2. Prepare the face detector

Use OpenCV's face detector to detect faces in an image. In Python, you can use the following code to load the face detector:

import cv2  
  
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

Here you need to provide the path to the XML file (method in step 4) that contains the features used to detect faces. OpenCV provides several pretrained face detectors, you can choose any one of them.
insert image description here

3. Turn on the camera

Use OpenCV's VideoCapture class to open the camera. Here is a sample code:

import cv2  
  
cap = cv2.VideoCapture(0)

Here, cap is a VideoCapture object, which represents the open camera. 0 means the first camera.

4. Loop read frames and process

Use OpenCV's read() method to read frames from the camera. Here is a sample code:

import cv2  
  
cap = cv2.VideoCapture(0)  
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')  
  
while True:  
    ret, frame = cap.read()  
    if ret:  
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  
        faces_rects = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)  
        for (x, y, w, h) in face_rects:  
            cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)  
        cv2.imshow('Face Detection', frame)  
        if cv2.waitKey(1) & 0xFF == ord('q'):  
            break  
    else:  
        break
# 使用release()方法释放摄像头,并使用destroyAllWindows()方法关闭所有窗口
cap.release()  
cv2.destroyAllWindows()

Here, you need to use the haarcascade_frontalface_default.xml file, which is found in the installed opencv directory.

  • haarcascade_frontalface_default.xml file path
    C:\OpenCV\opencv\build\etc\haarcascades

  • Or download it on github:
    https://github.com/opencv/opencv/tree/master/data/haarcascades

We use the detectMultiScale() method to detect all faces in each frame and draw a rectangle on each face. We also display the result using the imshow() method. The waitKey() method waits for the user to press any key on the keyboard, then we use the break statement to exit the loop.

To sum up, the above are the basic steps for camera face recognition using Python 3 and OpenCV. You can modify and extend it according to your needs.
![Insert picture description here](https://img-blog.csdnimg.cn/077b697fc76f4f6e8fee0378a62f094d.png

Guess you like

Origin blog.csdn.net/weixin_44697721/article/details/131965621