在python中,即时通讯使用PIL加载gif。我提取第一帧,对其进行修改,然后放回去。我用以下代码保存修改后的gif
imgs[0].save('C:\\etc\\test.gif',
save_all=True,
append_images=imgs[1:],
duration=10,
loop=0)
其中imgs是组成gif的图像数组,持续时间是指帧之间的延迟(以毫秒为单位)。我想使持续时间值与原始gif相同,但是不确定如何提取gif的总持续时间或每秒显示的帧。
据我所知,gif的头文件不提供任何fps信息。
有谁知道我如何获得持续时间的正确值?
提前致谢
编辑:要求的gif示例:
从here检索。
最佳答案
在GIF文件中,每个帧都有自己的持续时间。因此,GIF文件没有通用的fps。 PIL supports this的方式是提供一个给出当前帧的info
的duration
格。您可以使用seek
和tell
遍历帧并计算总持续时间。
这是一个示例程序,用于计算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'])