haar级联没有检测到

haar cascade no detection

我正在使用 cv2 中使用 Haar 级联代码的示例面部和眼睛检测。 现在我正在尝试修改代码,以便在未检测到面部时触发一些代码。

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]

    eyes = eye_cascade.detectMultiScale(roi_gray)
    for (ex, ey, ew, eh) in eyes:
        cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)

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

所以如果检测到级联:什么也不做,否则:这里有一些代码。 有人可以帮忙吗?

我对 the documentation 的理解是你的变量 faces 应该保存一个包含矩阵的检测到的对象列表,然后你尝试在你的 for 循环中用矩形绘制,所以我会这样做:

 faces = face_cascade.detectMultiScale(gray, 1.3, 5)

 if not faces:
     # do your code
 else:
     for (x, y, w, h) in faces:
         # Rest of the code