python3.5 opencv3显示视频fps

时间:2024-03-04 12:00:31

由于要进行多路视频的处理,所以fps就很重要

  fps介绍

模板:

  1.获取某一时刻的fps

 

import time

while True:
    start_time = time.time() # start time of the loop

    ########################
    # your fancy code here #
    ########################

    print("FPS: ", 1.0 / (time.time() - start_time)) # FPS = 1 / time to process loop

 

   2.每一秒获取一次

 

import time

start_time = time.time()
x = 1 # displays the frame rate every 1 second
counter = 0
while True:

    ########################
    # your fancy code here #
    ########################

    counter+=1
    if (time.time() - start_time) > x :
        print("FPS: ", counter / (time.time() - start_time))
        counter = 0
        start_time = time.time()

 3.实例

  (1)读取目录中的某一个视频

 

import time
import cv2
cap = cv2.VideoCapture("../video/basketball1.mp4")
start_time = time.time()
x = 1 # displays the frame rate every 1 second
counter = 0
while True:

    ret, frame = cap.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow(\'frame\', gray)
    if cv2.waitKey(1) & 0xFF == ord(\'q\'):
        break
    counter += 1
    if (time.time() - start_time) > x:
        print("FPS: ", counter / (time.time() - start_time))
        counter = 0
        start_time = time.time()
cap.release()
cv2.destroyAllWindows()

 

   运行效果

 

  其实把fps显示到窗口上更人性化一点,于是我把原来的putTest()方法和这个结合了一下,中间format里面转化了一下类型

 

import time
import cv2
cap = cv2.VideoCapture("../video/basketball1.mp4")
start_time = time.time()
x = 1 # displays the frame rate every 1 second
counter = 0
while True:

    ret, frame = cap.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    if cv2.waitKey(1) & 0xFF == ord(\'q\'):
        break
    counter += 1#记录经过多少秒
    if (time.time() - start_time) > x:
        cv2.putText(gray, "FPS {0}" .format(str(counter / (time.time() - start_time))), (10, 230), 6, 2, (255, 0, 255), 3)
        #cv2.putText(gray, "FPS %s" % str(counter / (time.time() - start_time)), (10, 130), 6, 5, (255, 0, 255), 5)
        #cv2.putText(gray, "Hello World!", (400, 50), cv2.FONT_HERSHEY_PLAIN, 2.0, (0, 0, 255), 2)
        cv2.imshow(\'frame\', gray)
        print("FPS: ", counter / (time.time() - start_time))
        #print(type(str(counter / (time.time() - start_time))))
        #print(type(counter / (time.time() - start_time)))
        counter = 0
        start_time = time.time()
cap.release()
cv2.destroyAllWindows()

 

 运行结果,fps数据每一秒都会刷新一下