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实现批量改文件名称的方法
May 25 Python
Python实现合并字典的方法
Jul 07 Python
python实现搜索本地文件信息写入文件的方法
Feb 22 Python
Python scikit-learn 做线性回归的示例代码
Nov 01 Python
python实现微信发送邮件关闭电脑功能
Feb 22 Python
Django接收post前端返回的json格式数据代码实现
Jul 31 Python
8段用于数据清洗Python代码(小结)
Oct 31 Python
python进程池实现的多进程文件夹copy器完整示例
Nov 27 Python
解决Python使用列表副本的问题
Dec 19 Python
VS2019+python3.7+opencv4.1+tensorflow1.13配置详解
Apr 16 Python
一篇文章搞懂python的转义字符及用法
Sep 03 Python
Python使用Kubernetes API访问集群
May 30 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
PHP 日,周,月点击排行统计
2012/01/11 PHP
PhpDocumentor 2安装以及生成API文档的方法
2014/05/21 PHP
php实现不通过扩展名准确判断文件类型的方法【finfo_file方法与二进制流】
2017/04/18 PHP
使用js实现一个可编辑的select下拉列表
2014/02/20 Javascript
js 判断图片是否加载完以及实现图片的预下载
2014/08/14 Javascript
BootStrap Progressbar 实现大文件上传的进度条的实例代码
2016/06/27 Javascript
深入理解JS中的Function.prototype.bind()方法
2016/10/11 Javascript
详解JavaScript模块化开发
2016/12/04 Javascript
微信小程序侧边栏滑动特效(左右滑动)
2017/01/23 Javascript
canvas实现图像截取功能
2017/02/06 Javascript
canvas压缩图片转换成base64格式输出文件流
2017/03/09 Javascript
AngularJS封装$http.post()实例详解
2017/05/06 Javascript
从parcel.js打包出错到选择nvm的全部过程
2018/01/23 Javascript
更优雅的微信小程序骨架屏实现详解
2019/08/07 Javascript
vue路由切换时取消之前的所有请求操作
2020/09/01 Javascript
vue使用openlayers实现移动点动画
2020/09/24 Javascript
[01:09:20]NB vs NAVI Supermajor小组赛A组 BO3 第二场 6.2
2018/06/03 DOTA
python冒泡排序算法的实现代码
2013/11/21 Python
Flask框架的学习指南之用户登录管理
2016/11/20 Python
网站渗透常用Python小脚本查询同ip网站
2017/05/08 Python
python中模块的__all__属性详解
2017/10/26 Python
django 自定义filter 判断if var in list的例子
2019/08/20 Python
Python3将jpg转为pdf文件的方法示例
2019/12/13 Python
Selenium 安装和简单使用的实现
2020/12/04 Python
意大利在线购买隐形眼镜网站:VisionDirect.it
2019/03/18 全球购物
说出一些常用的类,包,接口
2014/09/22 面试题
外贸英语毕业生自荐信
2013/11/14 职场文书
新闻报道策划方案
2014/06/11 职场文书
小学六一儿童节活动方案
2014/08/27 职场文书
2014年话务员工作总结
2014/11/19 职场文书
用Python写一个简易版弹球游戏
2021/04/13 Python
用Python简陋模拟n阶魔方
2021/04/17 Python
Python 数据科学 Matplotlib图库详解
2021/07/07 Python
css3属性选择器 “~”(波浪号) “,”(逗号) “+”(加号)和 “>”(大于号)
2022/04/19 HTML / CSS
MySQL约束(创建表时的各种条件说明)
2022/06/21 MySQL
Apache Kafka 分区重分配的实现原理解析
2022/07/15 Servers