我在使用 HaarCascades 检测照片中的脸部时遇到问题。我收到此错误:
error: OpenCV(4.8.0) /io/opencv/modules/objdetect/src/cascadedetect.cpp:1389: error: (-215:Assertion failed) scaleFactor > 1 && _image.depth() == CV_8U in function 'detectMultiScale'
这是我的功能:
def face_detector(img):
color_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
face_classifier = cv2.CascadeClassifier(os.path.join(cv2.data.haarcascades, 'haarcascade_frontalface_default.xml'))
scale = 1.3
faces = face_classifier.detectMultiScale(color_img, scale, 5)
if len(faces) == 0:
while scale != 0.0:
x = 0.1
scale = scale - x
faces = face_classifier.detectMultiScale(color_img, scale, 5)
if len(faces) != 0:
for (x, y, w, h) in faces:
cv2.rectangle(color_img, (x, y), (x+w, y+h), (0, 255, 255), 2)
roi = color_img[y:y+h, x:x+w]
cv2_imshow(color_img)
cv2_imshow(roi)
return color_img, roi
for (x, y, w, h) in faces:
cv2.rectangle(color_img, (x, y), (x+w, y+h), (0, 255, 255), 2)
roi = color_img[y:y+h, x:x+w]
cv2_imshow(color_img)
cv2_imshow(roi)
return color_img, roi
return color_img, None
这种情况仅有时发生(并非所有图像)。我能做什么?
失败的断言是:
(-215:Assertion failed) scaleFactor > 1 && _image.depth() == CV_8U in function 'detectMultiScale'
两个条件都必须为真。至少其中有一个是假的。
scale
因子需要大于 1。您的代码将其减少到低于该值。
您的代码还会以不同的比例因子在同一图像上重复调用
detectMultiScale()
。这是不合理的。选择一个适当接近 1 的比例因子,然后仅运行一次检测。 1.3
可能迈得太大了。尝试 1.2
或 1.1
。不要走得太近,否则只会浪费时间而没有实际收益。