Home > Software engineering >  Python: use time.sleep with opencv without stopping the video footage
Python: use time.sleep with opencv without stopping the video footage

Time:10-30

Im using opencv for detecting a hand gesture (in this case, when i lift my index finger), when that happens it prints "hi", then i use time.sleep to pause the print for 1 second because it will print it until I put my index down, but time.sleep pauses the entire footage, so if i sleep 5 seconds, the footage wont run untile those 5 seconds have passed

What can I do to use the time.sleep without pausing the footage

while True:
  #all the opencv initial stuff
  #mediapipe functions for the hand detection

  if INDEX_UP:
     print("hi")
     time.sleep(2)
  
  cv2.imshow("Frame", frame)
  if cv2.waitKey(1) & 0xFF == 27: break

Im trying to use time.sleep inside the while loop im using for opencv, but the time.sleep pauses the footage until the time.sleep finish

CodePudding user response:

I tried to use 2 separate threads for the entire while loop and another one for the sleep, it´s not sleeping.

def sleep():
  time.sleep(2)

def main_loop():
  while True:
  #all the opencv initial stuff
  #mediapipe functions for the hand detection

  if INDEX_UP:
     print("hi")
     th.Thread(target=sleep).start()
  
  cv2.imshow("Frame", frame)
  if cv2.waitKey(1) & 0xFF == 27: break

th.Thread(target=main_loop).start()

CodePudding user response:

time.sleep() will block the thread execution by the amount of time provided. This is described in this answer by Nick Bastin and also you can find useful examples.

  • Related