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?