python-3.x - 无法计算输出视频流的 fps

标签 python-3.x opencv

我已经使用 Tensorflow 和 open cv 实现了实时对象检测,如 this post 中所述和 this GitHub repo .

对象检测运行良好,但我在实现 fps 计算器时遇到了问题。

这是我编写的代码:

import datetime


class FramesPerSecond:
    def __init__(self):
    self._startTime = None
    self._currentTime = None
    self._total_number_of_frames = 0

def start(self):
    # start timer
    self._startTime = datetime.datetime.now()
    return self

def stop(self):
    # stop times
    self._currentTime = datetime.datetime.now()

def update_frames(self):
    self._total_number_of_frames = self._total_number_of_frames + 1

def elapsed_time(self):
    return (datetime.datetime.now() - self._startTime).total_seconds()

def current_fps(self):
    return self._total_number_of_frames / self.elapsed_time()

current_fps 不是返回一个在视频流期间保持不变的值,而是返回一个在整个流中增加的值。

最佳答案

current_fps 函数返回一个随时间增加的值,因为 self._total_number_of_frames 属性将不断增加,而耗时将在每次循环迭代中或多或少保持不变。基本上,分子将永远增加,而分母将保持在一个范围内,从而导致值随时间增加。

为避免此问题,我们必须允许耗时函数随着帧数的增加而按比例增加,或者使用其他一些常量来衡量我们的 fps。让我们选择后者并保留一个单独的计数器变量。

所以你上面的代码可以这样重写:

import time  # The time module is easier for our purpose.


class FramesPerSecond:
    def __init__(self):
        self.startTime = None
        self.total_number_of_frames = 0
        self.counter = 0
        self.frameRate = 1  # The number of seconds to wait for each measurement.

    def start(self):
        self.startTime = time.time()  # Returns a UNIX timestamp.

    def update_frames(self):
        self.total_number_of_frames += 1

    def elapsed_time(self):
        return time.time() - self.startTime

    def current_fps(self):
        return self.counter / self.elapsed_time()  # We are measuring against the counter instead of no. of frames.


fps = FramesPerSecond()
fps.start()

while True:  # Your main loop.

    # Rest of your code here #
    fps.update_frames()

    fps.counter += 1  # Count will increase until the if condition executes.
    if fps.elapsed_time() > fps.frameRate:  # We measure the fps only after 1 second has passed.
        print("FPS: ", fps.current_fps()) # The frames per second. 
        fps.counter = 0  # reset the counter for next iteration.
        fps.start()  # reset the start time.

希望这对您有所帮助!

关于python-3.x - 无法计算输出视频流的 fps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55154753/

相关文章:

c++ - 带有fedora 23的Opencv Qt:程序意外完成

c++ - OpenCV 2.x 中像素访问的错误

python-3.x - 根据 .hdf5 中的权重和 .json 中的选项在 keras 中实例化 ELMo 模型

python - 类型错误 : '<' not supported between instances of 'State' and 'State' PYTHON 3

python - 从字符串中删除尾随的特殊字符

python - 检查变量是否不等于向量的任何元素

opencv - 如何实现更好的滑动窗口算法?

python-3.x - 在Python中编写循环函数的正确方法

c++ - OpenCV cvSaveImage Jpeg 压缩因子

c++ - 如何找出两个图像之间的对象差异?