Home > Enterprise >  How to print every x seconds while rest of code runs without being stopped?
How to print every x seconds while rest of code runs without being stopped?

Time:01-01

I've seen ways of using the time.sleep() function, however that stops the rest of the code from running.

I'm making a hand recognition script and want the video output to be hindered by a certain value being printed every second.

This is my code:

import cv2
from cvzone.HandTrackingModule import HandDetector
import time

cap = cv2.VideoCapture(0)
detector = HandDetector(maxHands=1, detectionCon=0.7)
length = 0
while True:
    success, img = cap.read()
    hands, img = detector.findHands(img)

    if hands:
        hand1 = hands[0]
        lmlist1 = hand1["lmList"]
        bbox = hand1["bbox"]
        cp1 = hand1["center"]
        HandType = hand1["type"]
        #fingers1 = detector.fingersUp(hand1)
        #print(fingers1)
        length, info, img = detector.findDistance(lmlist1[8], lmlist1[5], img)
        
    
    print(length)
    time.sleep(1)
        
    
    cv2.imshow("Image", img)
    cv2.waitKey(1) 
    if cv2.waitKey(1) == ord("q"):
        break
    

cap.release()
cv2.destroyAllWindows()

The problem is that because of:

print(length) 
time.sleep(1) 

the frame rate of the video is reduced to 1fps.

Is there a way to run the printing command so that it doesn't affect the frame rate?

Thanks.

CodePudding user response:

One way is to use time.time to measure how much time has passed (will print 'hi' every 5 seconds or so, this is less precise because if some part of the loop takes more time, it may print later than expected):

import time


start = time.time()
while True:
    # run some code

    current_time = time.time()
    if current_time - start >= 5:
        print('hi')
        start = current_time

Or use threading module to run a loop concurrently (will print 'hi' every 5 seconds, this is also more precise, because the time measurement is not affected by the speed of the "main" loop (as is the case with the above code)):

import time
import threading


def loop():
    while True:
        time.sleep(5)
        print('hi')


threading.Thread(target=loop).start()

while True:
    # run some code
    pass  # this can be removed after you add the actual code
  • Related