OpenCV Facial Detection come ups with this error

£可爱£侵袭症+ 提交于 2021-02-11 16:55:38

问题


I keep getting this error:

faces = face_cascade.detectMultiScale(gray, 1.3, 5)
cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-wvn_it83\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'

when trying to run this code

import cv2
import numpy as np

face_cascade = cv2.CascadeClassifier('haarcascase_frontalface_default.xml')

cap = cv2.VideoCapture(0)

while 1:
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]

    cv2.imshow('img', img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

I found the code in [this[(https://www.youtube.com/watch?v=88HdqNDQsEk&t=432s) YouTube video.


回答1:


Perhaps the haarcascase_frontalface_default.xml file is missing or the path has to be specified in another way.

https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml

https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml

Either the .xml could be in the directory of the script and you call it from it, or you may specify absolute path.

Both worked on my test run, that's with absolute path:

face_cascade = cv2.CascadeClassifier(r"Z:\py\haarcascade_frontalface_default.xml")

See:

error: (-215) !empty() in function detectMultiScale




回答2:


I believe this is due to the missing .xml file. Can you check if the path your your .xml file is correct?

Or do you start this program from elsewhere? Since the path will be start from where you run the program.

For example, even your python file is in the same directory as .xml file. If you run python from other directory like python folder/app.py It will throw the error. You will have to change your xml path to 'folder/model.xml' instead.



来源:https://stackoverflow.com/questions/65649556/opencv-facial-detection-come-ups-with-this-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!