简体   繁体   中英

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.

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. 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. Is there a way to use time.sleep in this case, or another method suitable for my needs?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM