我的代码每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
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