在opencv Python中仅捕获每个人的一张脸部照片并自动保存(无需按键)
我正在尝试使用 Python 中的 opencv 构建带有网络摄像头的人脸检测器。 当检测到人脸时,系统需要能够只捕获每个人的一张脸部照片并自动保存(无需按键),直到该人离开画面并且另一个人进入,再次检测到该人脸并将其保存在一个图像文件。 我正在使用 while 循环来进行实时视频流和连续面部检测。我尝试创建一个内部 while 循环来保存面部照片,但它需要多个帧。
代码:
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap=cv2.VideoCapture(0)
while True:
ret, img=cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5, minSize=(150, 150), maxSize=(300, 300))
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
face_img_gray = gray[y:y+h, x:x+w]
face_img_color = img[y:y+h, x:x+w]
laplacian_var = cv2.Laplacian(face_img_gray, cv2.CV_64F).var()
#print(laplacian_var)
if laplacian_var > 140: # avoid blur frame capture
cv2.imwrite('Frame.jpg', face_img_color)
cv2.imshow('img', img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
I'm trying to build a face detector with webcam using opencv in Python.
When human face is detected, the system need to be able to capture only one photo of face per person and save it automatically (without pressing a key), until the person leaves the frame and another person enters and again his face detected and saved in an image file.
I'm using a while loop for the live video stream and the continous face detection. I tried to create an inner while loop for saving the face photo, but it takes multiple frames.
The code:
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap=cv2.VideoCapture(0)
while True:
ret, img=cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5, minSize=(150, 150), maxSize=(300, 300))
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
face_img_gray = gray[y:y+h, x:x+w]
face_img_color = img[y:y+h, x:x+w]
laplacian_var = cv2.Laplacian(face_img_gray, cv2.CV_64F).var()
#print(laplacian_var)
if laplacian_var > 140: # avoid blur frame capture
cv2.imwrite('Frame.jpg', face_img_color)
cv2.imshow('img', img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论