In this article, we share the specific code of Python OpenCV calling the camera to detect faces and take screenshots for your reference. The specific contents are as follows
Note: The OpenCV library needs to be installed in python, and the OpenCV face recognition model haarcascade_frontalface_alt. xml needs to be downloaded. The model can be downloaded in OpenCV-PCA-KNN-SVM_face_recognition.
Use OpenCV to call the camera to detect the face and take 100 consecutive screenshots
#-*- coding: utf-8 -*-
# import Advance openCV Library of
import cv2
### Call the computer camera to detect the face and take a screenshot
def CatchPICFromVideo(window_name, camera_idx, catch_pic_num, path_name):
cv2.namedWindow(window_name)
# Video source, which can come from 1 Saved video, or directly from USB Camera
cap = cv2.VideoCapture(camera_idx)
# Tell OpenCV Using a face recognition classifier
classfier = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
# The color of the border to be drawn after recognizing the face, RGB Format , color Yes 1 An array that cannot be added or deleted
color = (0, 255, 0)
num = 0
while cap.isOpened():
ok, frame = cap.read() # Read 1 Frame data
if not ok:
break
grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Converts the current frame image to a grayscale image
# Face detection, 1.2 And 2 They are the scaling ratio of the picture and the number of effective points to be detected
faceRects = classfier.detectMultiScale(grey, scaleFactor = 1.2, minNeighbors = 3, minSize = (32, 32))
if len(faceRects) > 0: # Greater than 0 A face is detected
for faceRect in faceRects: # Box each separately 1 Zhang Face
x, y, w, h = faceRect
# Save the current frame as a picture
img_name = "%s/%d.jpg" % (path_name, num)
#print(img_name)
image = frame[y - 10: y + h + 10, x - 10: x + w + 10]
cv2.imwrite(img_name, image,[int(cv2.IMWRITE_PNG_COMPRESSION), 9])
num += 1
if num > (catch_pic_num): # Exit the loop if the specified maximum save quantity is exceeded
break
# Draw a rectangular frame
cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2)
# Shows how many face images you've captured so you can stand there and be photographed with a count in mind, without having to look at your eyes 1 Smear and wait
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame,'num:%d/100' % (num),(x + 30, y + 30), font, 1, (255,0,255),4)
# End the program beyond the specified maximum number of saves
if num > (catch_pic_num): break
# Display image
cv2.imshow(window_name, frame)
c = cv2.waitKey(10)
if c & 0xFF == ord('q'):
break
# Release the camera and destroy all windows
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
# Continuous section 100 Image, save in image In the folder
CatchPICFromVideo("get face", 0, 99, "/image")