使用OpenCV在python中进行FaceDetection

时间:2016-07-26 11:25:08

标签: python opencv

我编写了以下代码,以便在OpenCV下的python中检测“face / faces的存在”。

import cv2
import sys

faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)


if vc.isOpened(): # try to get the first frame
     rval, frame = vc.read()
else:
     rval = False

while rval:
     rval, frame = vc.read()

     gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
     faces = faceCascade.detectMultiScale(gray, 1.3, 5)
     for (x,y,w,h) in faces:
         frame = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)

     # Display the resulting frame
     cv2.imshow('Preview', frame)

     key = cv2.waitKey(20)
     if key == 27: # exit on ESC
        break

cv2.destroyWindow("preview")
cv2.destroyAllWindows()

我收到以下错误:

   /usr/bin/python3.4  /home/yas/PycharmProjects/Ch10_OpenCV/Example.py
   init done 
   opengl support available 
   OpenCV Error: Assertion failed (!empty()) in detectMultiScale, file    /home/yas/opencv-3.0.0/modules/objdetect/src/cascadedetect.cpp, line 1634
   Traceback (most recent call last):
   File "/home/yas/PycharmProjects/Ch10_OpenCV/Example.py", line 32, in <module>
   faces = faceCascade.detectMultiScale(gray, 1.3, 5)
   cv2.error: /home/yas/opencv-  3.0.0/modules/objdetect/src/cascadedetect.cpp:1634: error: (-215) !empty()    in function detectMultiScale


  Process finished with exit code 1

结果,网络摄像头窗口无法打开,并且确定没有检测到面部。我在Linux-Ubtunu下工作并使用Python解释器3.4.3。

这个错误是什么意思?怎么解决?感谢您分享您的意见

1 个答案:

答案 0 :(得分:0)

您必须在最后两行之前添加secondRequest。它会是这样的:

vc.release()