简体   繁体   中英

How should I delay my code without pausing my OpenCv screen?

This is my code: After running the cell the OpenCV screen pauses and then the timer gets executed how should use the timer without pausing the screen. It is caused by time.sleep() function but how should I add delay in my code? I tried many ways to do it. Is there another way that I can add a delay to my code?

#cap = cv2.VideoCapture(0)
cap = cv2.VideoCapture('KneeBend.mp4')
# Curl counter variables
counter = 0 
stage = None

## Setup mediapipe instance
with mp_pose.Pose(min_detection_confidence=0.5, min_tracking_confidence=0.5) as pose:
    while cap.isOpened():
        ret, frame = cap.read()
        
        # Recolor image to RGB
        image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        image.flags.writeable = False
      
        # Make detection
        results = pose.process(image)
    
        # Recolor back to BGR
        image.flags.writeable = True
        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
        
        # Extract landmarks
        try:
            landmarks = results.pose_landmarks.landmark
            
            # Get coordinates
            hip = [landmarks[mp_pose.PoseLandmark.LEFT_HIP.value].x,landmarks[mp_pose.PoseLandmark.LEFT_HIP.value].y]
            knee = [landmarks[mp_pose.PoseLandmark.LEFT_KNEE.value].x,landmarks[mp_pose.PoseLandmark.LEFT_KNEE.value].y]
            ankle = [landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value].x,landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value].y]
        
            
            # Calculate angle
            angle = calculate_angle(hip, knee, ankle)
            
            # Visualize angle
            cv2.putText(image, str(angle), 
                           tuple(np.multiply(knee, [640, 500]).astype(int)), 
                           cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA
                                )
            
            # Curl counter logic
           # if angle == 80:
            
            if angle > 140:
                stage = "Bend your leg"
            if angle < 95 and stage == "Bend your leg":
                stage="Very good, now hold it for 8 secs"
                
                timer_sec = 8
                for i in range(timer_sec):
                    print(str(timer_sec-i) + "seconds remaining")
                    time.sleep(1)
                else:
                    print('ended loop')
                
                
                
               
                counter +=1
                print(counter)
                
                                    
        except:
            pass
        
        # Render curl counter
        # Setup status box
      #  cv2.rectangle(image, (0,0), (640,50), (245,117,16), -1)
        
        # Rep data
        cv2.putText(image, 'REPS:', (30,90), 
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 2, cv2.LINE_AA)
        cv2.putText(image, str(counter), 
                    (80,95), 
                    cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2, cv2.LINE_AA)
        
        # Stage data
     #   cv2.putText(image, 'STAGE', (5,5), 
      #              cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,0), 1, cv2.LINE_AA)
        cv2.putText(image, stage, 
                    (20,50), 
                    cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2, cv2.LINE_AA)
        
        
        # Render detections
        mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_pose.POSE_CONNECTIONS,
                                mp_drawing.DrawingSpec(color=(245,117,66), thickness=2, circle_radius=2), 
                                mp_drawing.DrawingSpec(color=(245,66,230), thickness=2, circle_radius=2) 
                                 )               
        
        cv2.imshow('Mediapipe Feed', image)

        if cv2.waitKey(10) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()

Do not call sleep. That will make the GUI unresponsive.

Keep looping but watch the time ( time.time() or time.perf_counter() ). Store a timestamp at the beginning of the interval and continually calculate the difference of the current time to the first timestamp.

When enough time has passed, act on that.

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