简体   繁体   中英

Trigger cv2.imwrite when a face or multiple faces are detected

In Ubuntu 16.04 I am trying to detect a face on a live video and save that image using OpenCV and Python. Specifically, I want to save just one image per face detected until I press 'q'. So for each different face that is detected, another picture of it, is taken. In the following code, the script is taking a picture each second until I exit.

import cv2

# Import the cascade for face detection
face_cascade = cv2.CascadeClassifier('data/haarcascades/haarcascade_frontalface_default.xml')

# Access the webcam (every webcam has a number, the default is 0)
video = cv2.VideoCapture(0)

num = 0

while True:

# Capture frame-by-frame
    ret, frame = video.read()

# Detect faces in video
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

# Draw rectangles around faces
    for (x,y,w,h) in faces:
            cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
            roi_gray = gray[y:y+h, x:x+w]
            roi_color = frame[y:y+h, x:x+w]
# Display the image
    cv2.imshow('Video', frame)
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)        
        cv2.imwrite('opencv'+str(num)+'.jpg',frame)
            num = num+1
# Press q for exit
    if cv2.waitKey(1) & 0xFF == ord('q'):
# Write frame in file

        break
video.release()
cv2.destroyAllWindows()

Any suggestions?

As @Silencer commented, the answer depends on the meaning that you associate with "different face".

  1. If you want to actually recognize the faces as persons: One possibility is to actually create a database of detected faces (or their features) and then compare the faces in subsequent frames with those in the database. In this case, you need an algorithm that performs face recognition. OpenCV and dlib have libraries for this task.

  2. If you want to just record one photo for each appearance of a given face in front of the camera: record the size and location of the first set of faces that are detected when the program is run, and then check if the following frames contain faces that are similar in size and location (the frame rate has to be high for this to work). In this case you need a tracking algorithm to match faces correctly. If a face disappears from the scene and appears again later, it will be captured again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM