2016-04-06 76 views
2

我正在与我的大学进行人脸识别项目。如果在关闭网络摄像头之前自动检测到脸部,我想拍摄快照并保存。 我现在拥有的是开放式摄像机,如果检测到脸部并等待,按“q”拍摄快照并保存图像。 下面是代码:自动检测脸部并使用opencv拍摄快照

import numpy as np 
import cv2 
import time 

#import the cascade for face detection 
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') 



def TakeSnapshotAndSave(): 
    # access the webcam (every webcam has a number, the default is 0) 
    cap = cv2.VideoCapture(0) 

    while(True): 
     # Capture frame-by-frame 
     ret, frame = cap.read() 

     # to detect faces in video 
     gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 
     faces = face_cascade.detectMultiScale(gray, 1.3, 5) 

     for (x,y,w,h) in faces: 
      cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2) 
      roi_gray = gray[y:y+h, x:x+w] 
      roi_color = frame[y:y+h, x:x+w] 

     x = 0 
     y = 20 
     text_color = (0,255,0) 
     # write on the live stream video 
     cv2.putText(frame, "Press q when ready", (x,y), cv2.FONT_HERSHEY_PLAIN, 1.0, text_color, thickness=2) 


     # if you want to convert it to gray uncomment and display gray not fame 
     #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 

     # Display the resulting frame 
     cv2.imshow('frame',frame) 
     # press the letter "q" to save the picture 
     if cv2.waitKey(1) & 0xFF == ord('q'): 
      # write the captured image with this name 
      cv2.imwrite('try.jpg',frame) 
      break 

    # When everything done, release the capture 
    cap.release() 
    cv2.destroyAllWindows() 


if __name__ == "__main__": 
    TakeSnapshotAndSave() 

预先感谢您

+0

好主意,即时通讯试试吧,让你知道它是否有效。谢谢 –

回答

0

执行imwrite()中的(X,Y,W,H)的面孔:循环本身。如果你使用一个固定的文件名,你最后检测到的脸部将被保存,其余的将被覆盖。

0

我调整你的代码以保存10张图片只是为了测试,如果你想要无限的照片,只需改变while条件。所以在你的代码中,你覆盖了当前的图像,所以我改变了字符串参数,这样就有可能拍摄很多图片。

import numpy as np 
import cv2 
import time 

#import the cascade for face detection 
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') 

def TakeSnapshotAndSave(): 
    # access the webcam (every webcam has a number, the default is 0) 
    cap = cv2.VideoCapture(0) 

    num = 0 
    while num<10: 
     # Capture frame-by-frame 
     ret, frame = cap.read() 

     # to detect faces in video 
     gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 
     faces = face_cascade.detectMultiScale(gray, 1.3, 5) 

     for (x,y,w,h) in faces: 
      cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2) 
      roi_gray = gray[y:y+h, x:x+w] 
      roi_color = frame[y:y+h, x:x+w] 

     x = 0 
     y = 20 
     text_color = (0,255,0) 

     cv2.imwrite('opencv'+str(num)+'.jpg',frame) 
     num = num+1 

    # When everything done, release the capture 
    cap.release() 
    cv2.destroyAllWindows() 


if __name__ == "__main__": 
    TakeSnapshotAndSave()