本文实例讲述了python图像处理之gif动态图的解析与合成操作。分享给大家供大家参考,具体如下:
gif动态图是在现在已经司空见惯,朋友圈里也经常是一言不合就斗图。这里,就介绍下如何使用python来解析和生成gif图像。
一、gif动态图的合成
如下图,是一个gif动态图。
gif动态图的解析可以使用pil
图像模块即可,具体代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
#-*- coding: utf-8 -*-
import os
from pil import image
def analyseimage(path):
'''
pre-process pass over the image to determine the mode (full or additive).
necessary as assessing single frames isn't reliable. need to know the mode
before processing all frames.
'''
im = image. open (path)
results = {
'size' : im.size,
'mode' : 'full' ,
}
try :
while true:
if im.tile:
tile = im.tile[ 0 ]
update_region = tile[ 1 ]
update_region_dimensions = update_region[ 2 :]
if update_region_dimensions ! = im.size:
results[ 'mode' ] = 'partial'
break
im.seek(im.tell() + 1 )
except eoferror:
pass
return results
def processimage(path):
'''
iterate the gif, extracting each frame.
'''
mode = analyseimage(path)[ 'mode' ]
im = image. open (path)
i = 0
p = im.getpalette()
last_frame = im.convert( 'rgba' )
try :
while true:
print "saving %s (%s) frame %d, %s %s" % (path, mode, i, im.size, im.tile)
'''
if the gif uses local colour tables, each frame will have its own palette.
if not, we need to apply the global palette to the new frame.
'''
if not im.getpalette():
im.putpalette(p)
new_frame = image.new( 'rgba' , im.size)
'''
is this file a "partial"-mode gif where frames update a region of a different size to the entire image?
if so, we need to construct the new frame by pasting it on top of the preceding frames.
'''
if mode = = 'partial' :
new_frame.paste(last_frame)
new_frame.paste(im, ( 0 , 0 ), im.convert( 'rgba' ))
new_frame.save( '%s-%d.png' % (' '.join(os.path.basename(path).split(' . ')[:-1]), i), ' png')
i + = 1
last_frame = new_frame
im.seek(im.tell() + 1 )
except eoferror:
pass
def main():
processimage( 'test_gif.gif' )
if __name__ = = "__main__" :
main()
|
解析结果如下,由此可见改动态图实际上是由14张相同分辨率的静态图组合而成
二、gif动态图的合成
gif图像的合成,使用imageio
库(https://pypi.python.org/pypi/imageio)
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#-*- coding: utf-8 -*-
import imageio
def create_gif(image_list, gif_name):
frames = []
for image_name in image_list:
frames.append(imageio.imread(image_name))
# save them as frames into a gif
imageio.mimsave(gif_name, frames, 'gif' , duration = 0.1 )
return
def main():
image_list = [ 'test_gif-0.png' , 'test_gif-2.png' , 'test_gif-4.png' ,
'test_gif-6.png' , 'test_gif-8.png' , 'test_gif-10.png' ]
gif_name = 'created_gif.gif'
create_gif(image_list, gif_name)
if __name__ = = "__main__" :
main()
|
这里,使用第一步解析出来的图像中的8幅图,间副的间隔时间为0.1s,合成新的gif动态图如下:
希望本文所述对大家python程序设计有所帮助。
原文链接:https://blog.csdn.net/guduruyu/article/details/77540445