[英]error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'
[英]OpenCV-Python Error (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'
考虑以下代码:
import cv2
# define a video capture object
vid = cv2.VideoCapture(0, cv2.IMREAD_UNCHANGED)
classifier = cv2.CascadeClassifier(cv2.data.haarcascades +
'haarcascade_frontalface_default.xml')
while True:
# Capture the video frame
# by frame
ret, frame = vid.read()
faces = classifier.detectMultiScale(frame)
for face in faces:
# extract
x, y, width, height = face
x2 = x + width
y2 = y + height
# draw a rectangle over the pixels
cv2.rectangle(frame, (x, y), (x2, y2), (0, 0, 255), 1)
# show the image
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# keep the window open until we press a key
cv2.waitKey(0)
# close the window
cv2.destroyAllWindows()
有一个问题,当我运行这行代码时
faces = classifier.detectMultiScale(frame)
我总是得到同样的错误:
cv2.error: OpenCV(4.5.3) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-c2l3r8zm\opencv\modules\objdetect\src\cascadedetect.cpp:1689:
error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'
我已经尝试了我见过的所有解决方案,比如为分类器提供完整路径,但似乎没有任何效果。
这些文件在同一个文件夹中没有任何意义。
相对路径是相对于当前工作目录解析的,而不是脚本所在的目录。
此外,您的代码使用cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
这可能是绝对路径。
您应该检查该位置是否存在文件。
然后......总是错误检查。
您缺少几个错误检查。
classifier = cv2.CascadeClassifier...
之后,您必须检查是否成功:assert not classifier.empty()
这可能是这里的问题。 违反的断言(错误消息)检查了这种情况。
vid = cv2.VideoCapture...
您必须检查是否成功:assert vid.isOpened()
ret, frame = vid.read()
) 后,您必须检查是否成功:if not ret: break
可能您的文件在您指定的路径中不可用。 尝试打印路径以进行检查。 还要检查classifier.empty()
是否返回true
以了解文件是否为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.