Home > Enterprise >  How to update FPS dynamically on window title of cv2 in Python
How to update FPS dynamically on window title of cv2 in Python

Time:09-12

I am using python opencv to do some video related work. I am also calculating the FPS and showing it on top left corner of the cv2 window. Now instead of showing it in top left corner, I want to show it on window title. Below is the code:

import cv2
import datetime
import imutils

def GetCoord(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        print("X: {} | Y: {}".format(x, y))

winName = "My Project"
cv2.namedWindow(winName)
cv2.setMouseCallback(winName, GetCoord)

cap = cv2.VideoCapture(0)
fps_start_time = datetime.datetime.now()
fps = 0
total_frames = 0

while True:
    ret, frame = cap.read()
    frame = imutils.resize(frame, width=800)
    total_frames = total_frames   1
    fps_end_time = datetime.datetime.now()
    time_diff = fps_end_time - fps_start_time
    if time_diff.seconds == 0:
        fps = 0.0
    else:
        fps = (total_frames / time_diff.seconds)
    fps_text = "FPS: {:.2f}".format(fps)
    cv2.putText(frame, fps_text, (5, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)
    cv2.imshow(winName, frame)
    key = cv2.waitKey(1)
    if key == ord('q'):
        break

cv2.destroyAllWindows()

Instead of showing it on top left corner, I want to do something like the below:

cv2.imshow(winName   " FPS: {}".format(fps_text), frame)

But doing so, the application performs very strangely and keeps opening a new windows. Is there a way to achieve this?

CodePudding user response:

The Cause of the Problem:

In opencv each window has a unique name. The window is created with this name when you either call cv2.namedWindow, or implicitly when you call cv2.imshow with a new name.
By using:

cv2.imshow(winName   " FPS: {}".format(fps_text), frame)

You actually create new windows each time the fps_text is different than the ones before.

The Solution:

An opencv window also has a title property. By default the window title is the window unique name, but these are 2 different entities.

You can use cv2.setWindowTitle to modify the title:

fps_text = "{:.2f}".format(fps)
winTitle = winName   " FPS: {}".format(fps_text)
cv2.setWindowTitle(winName, winTitle)

Note that the window unique name does not change.

  • Related