error: (-215:Assertion failed) !empty() in function 'detectMultiScale'

在运行 opencv-python 官方示例中的人脸识别脚本时可能会遇到下面的错误:

Traceback (most recent call last):
  File "/Users/eggtargaryen/test.py", line 22, in 
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
cv2.error: OpenCV(3.4.2) /Users/travis/build/skvark/opencv-python/opencv/modules/objdetect/src/cascadedetect.cpp:1698: error: (-215:Assertion failed) !empty() in function 'detectMultiScale'

原因很简单,这两句里面的xml文件路径不对引起,应该将路径改为全局路径:

face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv.CascadeClassifier('haarcascade_eye.xml')

查找这两个文件的位置,官方文档已经说了该文件在opencv-python包的/data文件夹下,下面只要找到opencv-python包在哪里就可以了,运行下面的代码就可以显示该位置了

import cv2 as cv
print(cv.__file__)

运行代码,我显示如下内容:

/Library/Frameworks/Python.framework/Versions/3.6/bin/python3 /Users/eggtargaryen/test.py
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/cv2/cv2.cpython-36m-darwin.so

那么我的opencv-python包的位置就是/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/cv2/

可以试着查看该路径下有没有data文件夹:
error: (-215:Assertion failed) !empty() in function 'detectMultiScale'_第1张图片

最后将最开始的路径补全就OK了:

face_cascade = cv.CascadeClassifier('/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/cv2/data/haarcascade_frontalface_default.xml')
eye_cascade = cv.CascadeClassifier('/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/cv2/data/haarcascade_eye.xml')

你可能感兴趣的:(error: (-215:Assertion failed) !empty() in function 'detectMultiScale')