[英]Take automatically picture in OpenCV
I wrote the face recognition code in OpenCV. 我在OpenCV中编写了人脸识别代码。 I want the program to automatically take a picture when it detects a face 我希望程序在检测到脸部时自动拍照
Below is whole code. 下面是完整的代码。
import cv2
face_cascade =
cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
video = cv2.VideoCapture(0)
while True:
ret, img = video.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.05,
minNeighbors=5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
cv2.imshow('img',img)
k = cv2.waitKey(1)
if k == ord('q'):
break
video.release()
cv2.destroyAllWindows()
When you do 当你做
ret, img = video.read()
you do take a picture. 你拍张照片。 Otherwise you won't be able to detect the faces in that frame, would you? 否则,您将无法检测到该帧中的面部,对吗?
I assume you asked about saving the frame as an image. 我假设您问过有关将框架另存为图像的问题。
You simply have to check if there are any faces, and save it using cv2.imwrite
. 您只需检查是否有面孔,然后使用cv2.imwrite
保存它。
The following code saves in the current directory the image, and the filenames are numbered in increasing order: 以下代码将图像保存在当前目录中,并且文件名按升序编号:
count = 0
while True:
ret, img = video.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.05,
minNeighbors=5)
if (len(faces) != 0)
cv2.imwrite('face_image_%d.png' % count)
count += 1
There are probably better ways, but this shows the basic concept. 可能有更好的方法,但这显示了基本概念。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.