python中的cvlib库已经很成熟,研究社区中的许多人都在使用它。我注意到,如果没有face检测到( for )循环停止,如果我有以下代码:
cap = cv2.VideoCapture(0)
if not (cap.isOpened()):
print('Could not open video device')
#To set the resolution
vid_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
vid_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
while(True):
ret, frame = cap.read()
if not ret:
continue
faces, confidences = cv.detect_face(frame)
# loop through detected faces and add bounding box
for face in faces:
(startX,startY) = face[0],face[1]
(endX,endY) = face[2],face[3]
cv2.rectangle(frame, (startX,startY), (endX,endY), (0,255,0), 2)
crop_img = frame[startY-5:endY-5, startX-5:endX-5]```
print(faces)
cv2.imshow('object detected',frame)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()当我打印(脸)的时候,输出会是这样的
[[392, 256, 480, 369]]
[[392, 256, 478, 369]]
[[392, 255, 478, 370]]
.
.
.
[[392, 255, 478, 370]]然而,一旦我挡住相机或将头移开,因为没有检测到脸,for循环就会冻结或暂停,直到它看到要检测到的脸。
我需要一个if语句或任何其他条件来检查这个冻结或暂停来产生其他的事情。
发布于 2020-04-09 11:09:50
我已经找到了这个问题的答案,如果我们在for循环之前添加一个if语句,因为faces是int,它会产生1,2,3,取决于摄像机前面有多少张脸。
if len(faces) == 0:
print('no faces')
print(faces) # going to print 0
else:
for face in faces:
(startX,startY) = face[0],face[1]
(endX,endY) = face[2],face[3]
crop_img = frame[startY-5:endY-5, startX-5:endX-5]
cv2.rectangle(frame, (startX,startY), (endX,endY), (0,255,0), 2)
cv2.imshow('object detected',frame)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()发布于 2020-04-09 06:10:17
您只显示检测到面部的帧。如果没有检测到人脸,则您正在看到检测到面部的最后一个帧,直到下一次在下一帧中检测到人脸。
将imshow移出for循环。例如,
# loop through detected faces and add bounding box
for face in faces:
(startX,startY) = face[0],face[1]
(endX,endY) = face[2],face[3]
cv2.rectangle(frame, (startX,startY), (endX,endY), (0,255,0), 2)
crop_img = frame[startY-5:endY-5, startX-5:endX-5]
print(faces)
cv2.imshow('object detected',frame)
k = cv2.waitKey(30) & 0xff
if k == 27:
break查看完整的示例这里。
https://stackoverflow.com/questions/61110790
复制相似问题