Search code examples
pythonyolov5

How can I write FPS showing code in YOLOv5


I just started to learn YOLOv5. When I write --source 0 in cmd and see myself in the screen I got very excited. I want to add a FPS showing code. I searched it on the internet. I find a code that shows FPS on webcam but I couldn't make them work together with YOLOv5. How should I put this code in Yolo?

The code that showing FPS:

webcam_cap = cv2.VideoCapture(0)

fps_cap_start_time = 0
fps_cap=0

while True:
    rec, frame = webcam_cap.read()

    fps_cap_end_time = time.time()
    time_diff = fps_cap_end_time - fps_cap_start_time
    fps_cap = 1/(time_diff)
    fps_cap_start_time = fps_cap_end_time

    fps_text = "FPS:  {:.2f}".format(fps_cap)

    cv2.putText(frame, fps_text, (5, 30), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,255), 1)

    cv2.imshow("webcam_cap",frame)
    key = cv2.waitKey(1)

    if key == 81 or key == 113:
        break
webcam_cap.release()
print('code complete')

Solution

  • You can use the time module to keep track of the FPS.

    from time import time
    

    and create a global variable called loop_time which will grab the current time

    loop_time = time()
    

    Then in your while loop you can print the FPS using the following:

    while True:
    if time() - loop_time > 0:
        print('FPS: {}'.format(1 / (time() - loop_time)))
    loop_time = time()
    

    The output should look something like: "FPS: 999.1195807527394".

    In your code it should look something like

    webcam_cap = cv2.VideoCapture(0)
    
    loop_time = time()
    
    while True:
        rec, frame = webcam_cap.read()
    
        fps_text = 1/(time() - loop_time)
        print('FPS: {}'.format(fps_text)
        loop_time = time()
    
        cv2.putText(frame, fps_text, (5, 30), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,255), 1)
    
        cv2.imshow("webcam_cap",frame)
        key = cv2.waitKey(1)
    
        if key == 81 or key == 113:
            break
    webcam_cap.release()
    print('code complete')