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

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

问题描述

在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.

据我所知,gif的头文件没有提供任何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示例:

摘录自此处.

推荐答案

在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'])

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

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