在 python 中每秒获取 gif 的帧数?

Get frames per second of a gif in python?

在 python 中,我正在使用 PIL 加载 gif。我提取第一帧,修改它,然后放回去。我用下面的代码保存修改后的 gif

imgs[0].save('C:\etc\test.gif',
           save_all=True,
           append_images=imgs[1:],
           duration=10,
           loop=0)

其中 imgs 是构成 gif 的图像数组,duration 是帧之间的延迟(以毫秒为单位)。我想让持续时间值与原始 gif 相同,但我不确定如何提取 gif 的总持续时间或每秒显示的帧数。

据我所知,gifs的头文件不提供任何fps信息。

有谁知道我如何获得正确的持续时间值?

提前致谢

编辑:请求的 gif 示例:

检索自 here

在 GIF 文件中,每一帧都有自己的持续时间。所以 GIF 文件没有通用的 fps。 PIL supports this 的方法是提供一个 info 字典,它给出当前帧的 duration。您可以使用 seektell 遍历帧并计算总持续时间。

这是一个计算 GIF 文件每秒平均帧数的示例程序。

import os
from PIL import Image

FILENAME = os.path.join(os.path.dirname(__file__),
                        'Rotating_earth_(large).gif')

def get_avg_fps(PIL_Image_object):
    """ Returns the average framerate of a PIL Image object """
    PIL_Image_object.seek(0)
    frames = duration = 0
    while True:
        try:
            frames += 1
            duration += PIL_Image_object.info['duration']
            PIL_Image_object.seek(PIL_Image_object.tell() + 1)
        except EOFError:
            return frames / duration * 1000
    return None

def main():
    img_obj = Image.open(FILENAME)
    print(f"Average fps: {get_avg_fps(img_obj)}")

if __name__ == '__main__':
    main()

如果您假设 duration 对于所有帧都是相等的,您可以这样做:

print(1000 / Image.open(FILENAME).info['duration'])