gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:36:49 35 4
gpt4 key购买 nike

在 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 示例:

enter image description here

取自 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'])

关于python - 在 python 中获取 gif 的每秒帧数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53364769/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com