[英]time.sleep for only a part of the code inside infinite while loop
I'm working with a code that analyzes frames from a live stream with OpenCV and if a condition is met saves the current frame to file. 我正在使用通过OpenCV分析实时流中的帧的代码,如果满足条件,则将当前帧保存到文件中。
The infinite loop to analyze the video frame by frame is something like this: 用于逐帧分析视频的无限循环如下所示:
while True:
ret,frame = stream.read()
if conditionisMet :
pil_image = Image.fromarray(frame)
pil_image.save("/path/to/folder/image.jpg")
cv2.imshow("LiveStream", frame)
What I want to add is that if the condition is met again too soon (20-30 sec) the image does not have to be saved and the while loop has to grab another frame and continue its work. 我要补充的是,如果再次过快地满足条件(20-30秒),则不必保存图像,而while循环必须获取另一帧并继续其工作。 I've tried with
time.sleep(30.0)
inside the if statement but it blocks the while loop waiting for the 30 sec to pass. 我已经尝试在if语句中使用
time.sleep(30.0)
,但是它阻塞了while循环,等待30秒过去。 Is there a way to use time.sleep
in this case, or another method suitable for my needs? 在这种情况下,是否可以使用
time.sleep
或其他适合我需要的方法?
Thanks in advance 提前致谢
you could do something like this: 您可以执行以下操作:
last_grab=time.time()-30 # this to get things started
while True:
if condition and time.time()-last_grab > 30:
last_grab=time.time()
# Do things here
else:
continue
Just add a variable to keep track of your last saving time: 只需添加一个变量来跟踪您的上次保存时间:
last_save_time = time.time()
while True:
ret,frame = stream.read()
if conditionisMet and time.time() - last_save_time() > 20:
pil_image = Image.fromarray(frame)
pil_image.save("/path/to/folder/image.jpg")
# update last save time
last_save_time = time.time()
cv2.imshow("LiveStream", frame)
Why not just capture the amount of time running then save image if greater than the given amount of time.... 为什么不只是捕获运行时间,如果大于给定时间,则保存图像。
a = dt.now()
b = dt.now()
c = b - a
if c < x:
do something
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.