使用Open CV断言失败

时间:2019-12-09 22:00:32

标签: python python-3.x opencv

我是openCV的新手,正在尝试让openCV在带Python 3.8的Win7上运行我的USB网络摄像头。我有here的基本教程,是由同一作者here从Raspberry Pi cam修改而来的。 这是

#!/usr/bin/python3

import time
import numpy as np
import cv2


#point to the haar cascade file in the directory
cascPath = "haarcascade.xml"
faceCascade = cv2.CascadeClassifier(cascPath)

#start the camera
video_capture = cv2.VideoCapture(0)

#give camera time to warm up
time.sleep(0.1)

#start video frame capture loop
while True:
  # take the frame, convert it to black and white, and look for facial features
  ret, frame = video_capture.read()

  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

  # use appropriate flag based on version of OpenCV
  if int(cv2.__version__.split('.')[0]) >= 3:
    cv_flag = cv2.CASCADE_SCALE_IMAGE
  else:
    cv_flag = cv2.cv.CV_HAAR_SCALE_IMAGE

  faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.1,
    minNeighbors=5,
    minSize=(30, 30),
    flags=cv_flag
  )

  #for each face, draw a green rectangle around it and append to the image
  for (x, y, w, h) in faces:
    cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

  #display the resulting image
  cv2.imshow('Video', frame)

  #set "q" as the key to exit the program when pressed
  if cv2.waitKey(1) & 0xFF == ord('q'):
    break


# clear the stream capture
video_capture.release()
cv2.destroyAllWindows()

它应该是开箱即用的,但是我收到下面的错误,我不确定为什么。 CV_flag和grey具有数据,其他参数已填充。任何想法。

C:\Users\Ghoul>py D:\LearnPython\open_cv_face_track_test.py -3.8
[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (674) 
SourceReaderCB::~SourceReaderCB
 terminating async callback
Traceback (most recent call last):
  File "D:\LearnPython\open_cv_face_track_test.py", line 31, in <module>
    faces = faceCascade.detectMultiScale(
cv2.error: OpenCV(4.1.2) C:\projects\opencv- 
python\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Ass
ertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'

1 个答案:

答案 0 :(得分:1)

faceCascade分类器为空,这意味着它无法从提供的路径中检索分类器。

您可以替换行

cascPath = "haarcascade.xml"

具有:

cascPath = '../../haarcascade.xml'

,其中您提供cascPath的xml文件的完整路径。