我正在尝试使用开源教程中的OpenCV制作人脸检测程序。目标是从视频中检测人脸,其结果被用作每个人脸的模型。每个脸将保存在文件夹中,我有2个问题,当我尝试的程序:
-
OpenCV不仅捕捉人脸,而且捕捉整个视频
-
只拍摄一张照片,而需要多张(每帧)
#insert picture 1
有解决方案吗?
代码如下:
model = cv2.CascadeClassifier("../model/haarcascade_frontalface_alt2.xml")
cap = cv2.VideoCapture('../video/videoplayback.mp4') #Video
while True:
ret, image = cap.read()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
bounding_box = model.detectMultiScale(gray, scaleFactor=1.01,
minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)
for (x, y, w, h) in bounding_box:
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
image2 = image[y:(y+h),x:(x+w)]
image3 = cv2.blur(image2, (40,40))
image[y:(y+h),x:(x+w)] = image3
cv2.imwrite("../output_model/videos/image.jpg", image)
cv2.imshow("hasil", image)
if cv2.waitKey(1) and 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()```
- 要只取人脸,就必须只取人脸的变量(它在image2变量中)。当它检测到视频时,你所做的就是模糊检测到的人脸,这样它就可以捡起模糊的部分。
image2 = image[y:(y+h),x:(x+w)]
cv2.imwrite("../output_model/videos/{}.jpg".format(counter), image2)
- 可以被加载人脸图像时执行的增量和循环欺骗。每个文件夹都用增量填充。下面是一个例子:
counter = 0 #Increment
while True:
ret, image = cap.read()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
bounding_box = detector_wajah.detectMultiScale(gray, scaleFactor=1.01,
minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)
for (x, y, w, h) in bounding_box:
counter+=1 #Increment
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
image2 = image[y:(y+h),x:(x+w)]
为了完整起见(有变量被改变了),如下所示:
import cv2
model = cv2.CascadeClassifier("../model/haarcascade_frontalface_alt2.xml")
cap = cv2.VideoCapture('../video/videoplayback.mp4') #Video
counter = 0
while True:
ret, image = cap.read()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
bounding_box = model.detectMultiScale(gray, scaleFactor=1.01,
minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)
for (x, y, w, h) in bounding_box:
counter+=1
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
face = image[y:(y+h),x:(x+w)]
cv2.imwrite("../output_model/videos/{}.jpg".format(counter), face)
blur_face = cv2.blur(face, (40,40))
image[y:(y+h),x:(x+w)] = blur_face
cv2.imshow("hasil", image)
if cv2.waitKey(1) and 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()