错误:(-215:断言失败)函数“ cv :: CascadeClassifier :: detectMultiScale”中的!empty()

时间:2019-09-09 13:09:07

标签: python opencv

我正在尝试在python中使用opencv尝试使用此示例人脸检测程序。但是detectMultiscale函数似乎出现错误。代码为:

import cv2
import sys

imagePath = sys.argv[1]
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
image = cv2.imread('face.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

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

)

print("Found {0} faces!".format(len(faces)))


for (x, y, w, h) in faces:
    cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)

cv2.imshow("Faces found", image)
cv2.waitKey(0)

这是代码。文件名为main.py。我将所有资源都放在Myproject文件下。当尝试从提示符下运行它时,出现此错误。

C:\Myproject>python main.py face.jpg
Traceback (most recent call last):
  File "main.py", line 21, in <module>
    minSize=(30, 30)
cv2.error: OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'

感谢阅读并帮助我解决了这个问题。

2 个答案:

答案 0 :(得分:0)

您的face.jpg路径错误(请检查它是否在同一文件夹中)。另外,faceCascade的路径是imagePath + cascPath

答案 1 :(得分:0)

使用此

import cv2

faceCascade=cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
img=cv2.imread('image\\my1.jpg')
imgGray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(imgGray,1.1,4)
for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
cv2.imshow("image",img)
cv2.waitKey(0)

它将帮助您进行正确的面部检测