我希望我的程序在倒计时结束后捕获图像。但在倒计时期间,我想让它向我展示现场摄像头。这是我的代码。
import cv2
import time
cam = cv2.VideoCapture(0)
countdown=3
img_counter = 0
cv2.namedWindow("test")
ret, frame = cam.read()
cv2.imshow("test", frame)
img_name = "example.png"
while countdown >0:
time.sleep(1)
print(countdown)
countdown -=1
if countdown == 0:
cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))
cam.release()
cv2.destroyAllWindows()
答案 0 :(得分:1)
您需要的是waitKey函数。它保存代码的执行,其中包含参数中指定的毫秒的数量。因此,如果您想等待3秒钟,您可以减少毫秒而不是秒,如下所示:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
seconds = 3
millis = seconds * 1000
while (millis > 0):
# Capture frame-by-frame
ret, frame = cap.read()
millis = millis - 10
# Display the resulting frame
cv2.imshow('video recording', frame)
if cv2.waitKey(10) & 0xFF == ord('q'):
#this method holds execution for 10 milliseconds, which is why we
#reduce millis by 10
break
#once the while loop breaks, write img
img_name = "example.png"
cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))