运行OpenCV给了我一个级联。cpp:1698错误:(215:断言失败)!函数“detectMultiScale”中的empty()

2024-10-17 04:21:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用opencvpython在我的Raspberry Pi 3上进行人脸检测。该程序应该使用从连接的网络摄像头抓取的帧。 在faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")行中,我得到以下错误:

Traceback (most recent call last):
  File "2webcam_cv3.py", line 32, in <module>
    minSize=(30, 30)
cv2.error: OpenCV(3.4.3) /home/pi/opencv-python/opencv/modules/objdetect/src/cascadedetect.cpp:1698: error: (-215:Assertion failed) !empty() in function 'detectMultiScale'

我已经读到其他问题,错误意味着XML文件无法加载。你知道吗

我尝试了文件系统中的直接链接,比如/home/pi/faceDetection/haarcascade_frontalface_default.xml,以及到github文件的链接。坦白说,我已经没有主意了。你知道吗

完整代码如下:

import cv2
import sys
import logging as log
import datetime as dt
from time import sleep


print(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
log.basicConfig(filename='webcam.log',level=log.INFO)

video_capture = cv2.VideoCapture(0)
anterior = 0

while True:
    if not video_capture.isOpened():
        print('Unable to load camera.')
        sleep(5)
        pass

    # Capture frame-by-frame
    ret, frame = video_capture.read()

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

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

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    if anterior != len(faces):
        anterior = len(faces)
        log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))


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


    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

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

# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()

print(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")返回/usr/local/lib/python3.7/dist-packages/cv2/data/haarcascade_frontalface_default.xml,这是一个非空文件。你知道吗

预期结果:一个包含摄像头流的窗口,包括检测到的人脸上的矩形

结果:错误

  File "2webcam_cv3.py", line 32, in <module>
    minSize=(30, 30)
cv2.error: OpenCV(3.4.3) /home/pi/opencv-python/opencv/modules/objdetect/src/cascadedetect.cpp:1698: error: (-215:Assertion failed) !empty() in function 'detectMultiScale' ```

Tags: inimportlogdefaultdataerrorxmlcv2