我正在尝试使用OpenCV从一个开源教程中制作一个人脸检测程序。目标是从视频中检测人脸,并将结果用作每个人的脸部模型。每个脸部将被保存到一个文件夹中,当我尝试运行程序时遇到了两个问题:
-
OpenCV不仅捕捉了人脸,还捕捉了整个视频
-
只捕捉了一张图片,而需要捕捉多张(每帧)
#insert picture 1
有什么解决方案吗?
这是代码:
model = cv2.CascadeClassifier("../model/haarcascade_frontalface_alt2.xml")cap = cv2.VideoCapture('../video/videoplayback.mp4') #Videowhile 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'): breakcap.release()cv2.destroyAllWindows()
回答:
- 要只捕捉人脸,需要使用仅从人脸获取的变量(在image2变量中)。当检测到视频时,您所做的就是模糊检测到的人脸,以便它可以捕捉到模糊的部分。
image2 = image[y:(y+h),x:(x+w)]cv2.imwrite("../output_model/videos/{}.jpg".format(counter), image2)
- 可以通过在加载人脸图像时执行的增量和循环来解决。每个文件夹都用增量填充。这里有一个例子:
counter = 0 #Incrementwhile 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 cv2model = cv2.CascadeClassifier("../model/haarcascade_frontalface_alt2.xml")cap = cv2.VideoCapture('../video/videoplayback.mp4') #Videocounter = 0while 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'): breakcap.release()cv2.destroyAllWindows()