尝试检测人脸时断言失败 215 错误

assertion failed 215 error when trying to detect faces

我正在使用 OpenCV 和 Python 来尝试使用 multidetect 检测人脸,但它似乎有问题。

这是我的代码:

#import required libraries
import cv2
import time

#point to the haar cascade file in the directory
cascPath = "haarcascade.xml"
#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
    faceCascade = cv2.CascadeClassifier(cascPath)
    ret, frame = video_capture.read()
    if not ret: break
    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()

这是我遇到的错误:

faces = faceCascade.detectMultiScale(
cv2.error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-_8k9tw8n\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'

解决方案:

你的错误的重要部分是:

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

基本上问题是在给定目录中找不到文件或者可能是格式问题。因此,尝试再次下载文件或使用 opencv pip 软件包附带的文件,如下所示:

faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')