我的代码每2秒捕获一次图像。但是问题在于它无限地运行。我需要脚本在某个时间段终止或关闭(例如,在50秒后终止或关闭)。我尝试使用 sleep(),但是怀疑不会终止整个脚本或关闭整个脚本,它只是使脚本进入睡眠状态! 希望有人可以帮助我一段时间后终止脚本!
我的脚本:
import cv2
import numpy
import time
capture = cv2.VideoCapture(0)
capture.set(3, 640)
capture.set(4, 480)
img_counter = 0
frame_set = []
start_time = time.time()
while True:
ret, frame = capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if time.time() - start_time >= 2:
img_name = "FaceFrame{}.jpg".format(img_counter)
cv2.imwrite(img_name, frame)
print("{} written!".format(img_counter))
start_time = time.time()
img_counter += 1
答案 0 :(得分:2)
actual_start_time = time.clock()
start_time = time.time()
while ((time.clock() - actual_start_time) < 50):
#do stuff
或者:
actual_start_time = time.clock()
start_time = time.time()
while True:
#do stuff
if (time.clock() - actual_start_time) > 50):
break