import cv2
import sys
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=2.0,
minNeighbors=5,A minSize=(30, 30),
flags = 0
#flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
# Write frame in file
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imwrite('only_face.jpg')
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
以上代码是从相机的实时馈送检测面部并仅保存一个面部的图像。我想保存从Feed中检测到的多个脸部的图像。它只保存一张脸的图像
答案 0 :(得分:1)
看看我在这里包括的内容:
import cv2
import sys
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
video_capture = cv2.VideoCapture(0)
increment = 0 #---Declare a variable that will increment for every image saved
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray, scaleFactor=2.0, minNeighbors=5,A minSize=(30, 30), flags = 0
#flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('Video', frame)
increment = increment + 1 #--- Initiate the increment variable
if cv2.waitKey(1) & 0xFF == ord('q'):
# Write frame in file
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imwrite('only_face' + str(increment) + '.jpg') #--- Here is where the increment variable is placed. It will be incremented for every face and thus saving every face that gets detected.
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
我已经包含了increment
变量,该变量会针对检测到的每个面部递增,从而分别保存每个图像。