在python中每秒获取gif的帧数? [英] Get frames per second of a gif in python?

查看:42
本文介绍了在python中每秒获取gif的帧数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In python, im loading in a gif with PIL. I extract the first frame, modify it, and put it back. I save the modified gif with the following code

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

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

Where imgs is an array of images that makes up the gif, and duration is the delay between frames in milliseconds. I'd like to make the duration value the same as the original gif, but im unsure how to extract either the total duration of a gif or the frames displayed per second.

据我所知,gifs的头文件没有提供任何fps信息.

As far as im aware, the header file of gifs does not provide any fps information.

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

Does anyone know how i could get the correct value for duration?

提前致谢

请求的 gif 示例:

Example of gif as requested:

取自此处.

推荐答案

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

In GIF files, each frame has its own duration. So there is no general fps for a GIF file. The way PIL supports this is by providing an info dict that gives the duration of the current frame. You could use seek and tell to iterate through the frames and calculate the total duration.

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

Here is an example program that calculates the average frames per second for a GIF file.

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 都相等,您可以这样做:

If you assume that the duration is equal for all frames, you can just do:

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

这篇关于在python中每秒获取gif的帧数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆