Python图像处理之gif动态图的解析与合成操作详解


Posted in Python onDecember 30, 2018

本文实例讲述了Python图像处理之gif动态图的解析与合成操作。分享给大家供大家参考,具体如下:

gif动态图是在现在已经司空见惯,朋友圈里也经常是一言不合就斗图。这里,就介绍下如何使用python来解析和生成gif图像。

一、gif动态图的合成

如下图,是一个gif动态图。

Python图像处理之gif动态图的解析与合成操作详解

gif动态图的解析可以使用PIL图像模块即可,具体代码如下:

#-*- 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张相同分辨率的静态图组合而成

Python图像处理之gif动态图的解析与合成操作详解

二、gif动态图的合成

gif图像的合成,使用imageio库(https://pypi.python.org/pypi/imageio)

代码如下:

#-*- 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图像处理之gif动态图的解析与合成操作详解

更多关于Python相关内容可查看本站专题:《Python数学运算技巧总结》、《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
python通过ftplib登录到ftp服务器的方法
May 08 Python
详解Python中find()方法的使用
May 18 Python
Python基于Matplotlib库简单绘制折线图的方法示例
Aug 14 Python
Python探索之实现一个简单的HTTP服务器
Oct 28 Python
http请求 request失败自动重新尝试代码示例
Jan 25 Python
浅谈python连续赋值可能引发的错误
Nov 10 Python
判断python对象是否可调用的三种方式及其区别详解
Jan 31 Python
不到20行代码用Python做一个智能聊天机器人
Apr 19 Python
基于python解线性矩阵方程(numpy中的matrix类)
Oct 21 Python
pandas和spark dataframe互相转换实例详解
Feb 18 Python
Python本地及虚拟解释器配置过程解析
Oct 13 Python
python实现学员管理系统(面向对象版)
Jun 05 Python
python爬虫获取小区经纬度以及结构化地址
Dec 30 #Python
python实现播放音频和录音功能示例代码
Dec 30 #Python
利用python实现简易版的贪吃蛇游戏(面向python小白)
Dec 30 #Python
python中partial()基础用法说明
Dec 30 #Python
python读取各种文件数据方法解析
Dec 29 #Python
python 读取鼠标点击坐标的实例
Dec 29 #Python
对python for 文件指定行读写操作详解
Dec 29 #Python
You might like
如何冲泡挂耳包咖啡?技巧是什么
2021/03/04 冲泡冲煮
一个ftp类(ini.php)
2006/10/09 PHP
Web程序工作原理详解
2014/12/25 PHP
PHP设计模式之工厂模式定义与用法详解
2018/04/03 PHP
php利用array_search与array_column实现二维数组查找
2019/07/08 PHP
密码框显示提示文字jquery示例
2013/08/29 Javascript
使用jQuery设置disabled属性与移除disabled属性
2014/08/21 Javascript
JavaScript九九乘法口诀表的简单实现
2016/10/04 Javascript
浅谈jquery上下滑动的注意事项
2016/10/13 Javascript
AngularJS实现表格的增删改查(仅限前端)
2017/07/04 Javascript
详解使用Vue Router导航钩子与Vuex来实现后退状态保存
2017/09/11 Javascript
详解tween.js的使用教程
2017/09/14 Javascript
使用JavaScript实现在页面中显示距离2017年中秋节的天数
2017/09/26 Javascript
Angular实现的进度条功能示例
2018/02/18 Javascript
AngularJS动态添加数据并删除的实例
2018/02/27 Javascript
localstorage实现带过期时间的缓存功能
2019/06/28 Javascript
layui table 表格模板按钮的实例代码
2019/09/21 Javascript
关于JS模块化的知识点分享
2019/10/16 Javascript
JS Web Flex弹性盒子模型代码实例
2020/03/10 Javascript
javascript实现拼图游戏
2021/01/29 Javascript
[04:03][TI9趣味短片] 小鸽子茶话会
2019/08/20 DOTA
Python基于回溯法子集树模板解决取物搭配问题实例
2017/09/02 Python
matplotlib在python上绘制3D散点图实例详解
2017/12/09 Python
Python爬虫实战:分析《战狼2》豆瓣影评
2018/03/26 Python
python print 按逗号或空格分隔的方法
2018/05/02 Python
详解python播放音频的三种方法
2019/09/23 Python
利用python画出AUC曲线的实例
2020/02/28 Python
Keras框架中的epoch、bacth、batch size、iteration使用介绍
2020/06/10 Python
python 读取、写入txt文件的示例
2020/09/27 Python
Python大批量搜索引擎图像爬虫工具详解
2020/11/16 Python
香港永安旅游网:Wing On Travel
2017/04/10 全球购物
学生档案自我鉴定
2013/10/07 职场文书
2015年科学教研组工作总结
2015/07/22 职场文书
学习新党章心得体会2016
2016/01/15 职场文书
写自招自荐信的绝招!
2019/04/19 职场文书
Python开发之QT解决无边框界面拖动卡屏问题(附带源码)
2021/05/27 Python