我有两个代码:第一个代码从实时Feed中检测到面部,第二个代码从WebCam中捕获图像。
我想在一个Python文件中附加这些代码,因此首先检测到面部,然后仅为面部捕获图像。
以下是代码:
捕捉脸部
import cv2
video_capture = cv2.VideoCapture(0)
# Capture frame
ret, frame = video_capture.read()
# Write frame in file
cv2.imwrite('image.jpg', frame)
# When everything is done, release the capture
video_capture.release()
检测到脸部
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,
minSize=(30, 30),
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'):
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
我希望这两个脚本在一个脚本中协同工作。
此致
答案 0 :(得分:0)
你很亲密!只需切片找到面x,y位置的框架数组。此外,如果要保存灰色图像,请将框架替换为灰色。
仅保存网络摄像头中的面部(颜色)
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,
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', frame[y:y+h,x:x+w])
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
正如@Antti Haapala所说,不要只是要求做一些事情ASAP
。告诉我们您尝试了哪种方式以及您面临的挑战。