SoFunction
Updated on 2024-11-07

Python OpenCV call to camera to detect faces and take screenshots

In this article, we share the example of Python OpenCV call camera to detect faces and screenshots of the specific code for your reference, the details are as follows

Note: You need to install the OpenCV library in python, and you also need to download the OpenCV face recognition model haarcascade_frontalface_alt.xml, the model can be found in theOpenCV-PCA-KNN-SVM_face_recognitionDownload in.

Using OpenCV to call the camera to detect faces and take 100 consecutive screenshots

#-*- coding: utf-8 -*-
# import into the openCV library
import cv2

### Call the computer camera to detect faces and take screenshots

def CatchPICFromVideo(window_name, camera_idx, catch_pic_num, path_name):
 (window_name)

 #Video source, either from a saved video or directly from a USB webcam
 cap = (camera_idx)

 #TellOpenCV to use face recognition classifiers
 classfier = ("haarcascade_frontalface_alt.xml")

 #The color of the border to be drawn after the face is recognized, 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

 grey = (frame, cv2.COLOR_BGR2GRAY) # Convert the current image to grayscale.

 # Face detection, 1.2 and 2 are the image scaling and the number of valid points to be detected respectively
 faceRects = (grey, scaleFactor = 1.2, minNeighbors = 3, minSize = (32, 32))
 if len(faceRects) > 0:  # greater than 0 then face is detected
  for faceRect in faceRects: # Frame each face individually
  x, y, w, h = faceRect

  # Save the current frame as an image
  img_name = "%s/%" % (path_name, num)
  #print(img_name)
  image = frame[y - 10: y + h + 10, x - 10: x + w + 10]
  (img_name, image,[int(cv2.IMWRITE_PNG_COMPRESSION), 9])

  num += 1
  if num > (catch_pic_num): # Exit the loop if the specified maximum number of saves is exceeded
   break

  # Draw rectangular boxes
  (frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2)

  #Displays how many face pictures are currently captured, so that when you stand there to be photographed, you have a number in mind and don't have to wait in the dark.
  font = cv2.FONT_HERSHEY_SIMPLEX
  (frame,'num:%d/100' % (num),(x + 30, y + 30), font, 1, (255,0,255),4)

  # Exceeds the specified maximum number of saves to end the program
 if num > (catch_pic_num): break

 #Display Image
 (window_name, frame)
 c = (10)
 if c & 0xFF == ord('q'):
  break

  # Release the camera and destroy all windows
 ()
 ()

if __name__ == '__main__':
 # 100 consecutive image cuts into the image folder
 CatchPICFromVideo("get face", 0, 99, "/image")

This is the whole content of this article.