gif图片拆帧及合成[python]实现
python版本2.7,使用PIL库,代码如下:
import ImageGrab # from PIL
import time
import string
from PIL import Image, ImageChops
from PIL.GifImagePlugin import getheader, getdata
import osdef intToBin(i):""" 把整型数转换为双字节 """# 先分成两部分,高8位和低8位i1 = i % 256i2 = int( i/256)# 合成小端对齐的字符串return chr(i1) + chr(i2)
def getheaderAnim(im):""" 生成动画文件头 """bb = "GIF89a"bb += intToBin(im.size[0])bb += intToBin(im.size[1])bb += "\x87\x00\x00" #使用全局颜色表return bb
def getAppExt(loops=0):""" 应用扩展,默认为0,为0是表示动画是永不停止"""bb = "\x21\xFF\x0B" # application extensionbb += "NETSCAPE2.0"bb += "\x03\x01"if loops == 0:loops = 2**16-1bb += intToBin(loops)bb += '\x00' # endreturn bbdef getGraphicsControlExt(duration=0.1):""" 设置动画时间间隔 """bb = '\x21\xF9\x04'bb += '\x08' # no transparancybb += intToBin( int(duration*100) ) # in 100th of secondsbb += '\x00' # no transparant colorbb += '\x00' # endreturn bbdef _writeGifToFile(fp, images, durations, loops):""" 把一系列图像转换为字节并存入文件流中"""# 初始化frames = 0previous = Nonefor im in images:if not previous:# 第一个图像# 获取相关数据palette = getheader(im)[1] #取第一个图像的调色板data = getdata(im)imdes, data = data[0], data[1:] header = getheaderAnim(im)appext = getAppExt(loops)graphext = getGraphicsControlExt(durations[0])# 写入全局头fp.write(header)fp.write(palette)fp.write(appext)# 写入图像fp.write(graphext)fp.write(imdes)for d in data:fp.write(d)else:# 获取相关数据 data = getdata(im) imdes, data = data[0], data[1:] graphext = getGraphicsControlExt(durations[frames])# 写入图像fp.write(graphext)fp.write(imdes)for d in data:fp.write(d) # 准备下一个回合previous = im.copy() frames = frames + 1fp.write(";") # 写入完成return framesdef writeGif(filename, images, duration=0.1, loops=0, dither=1):""" writeGif(filename, images, duration=0.1, loops=0, dither=1)从输入的图像序列中创建GIF动画images 是一个PIL Image [] 或者 Numpy Array"""images2 = []# 先把图像转换为PIL格式for im in images:if isinstance(im,Image.Image): #如果是PIL Imageimages2.append( im.convert('P',dither=dither) )elif np and isinstance(im, np.ndarray): #如果是Numpy格式if im.dtype == np.uint8:passelif im.dtype in [np.float32, np.float64]:im = (im*255).astype(np.uint8)else:im = im.astype(np.uint8)# 转换if len(im.shape)==3 and im.shape[2]==3:im = Image.fromarray(im,'RGB').convert('P',dither=dither)elif len(im.shape)==2:im = Image.fromarray(im,'L').convert('P',dither=dither)else:raise ValueError("图像格式不正确")images2.append(im)else:raise ValueError("未知图像格式")# 检查动画播放时间durations = [duration for im in images2]# 打开文件fp = open(filename, 'wb')# 写入GIFtry:n = _writeGifToFile(fp, images2, durations, loops)finally:fp.close()return n############################################################
## 将多帧位图合成为一幅gif图像
def images2gif( images, giffile, durations=0.05, loops = 1):seq = []for i in range(len(images)):im = Image.open(images[i])background = Image.new('RGB', im.size, (255,255,255))background.paste(im, (0,0))seq.append(background)frames = writeGif( giffile, seq, durations, loops)print frames, 'images has been merged to', giffile## 将gif图像每一帧拆成独立的位图
def gif2images( filename, distDir = '.', type = 'bmp' ):if not os.path.exists(distDir):os.mkdir(distDir)print 'spliting', filename,im = Image.open( filename )im.seek(0) # skip to the second framecnt = 0type = string.lower(type)mode = 'RGB' # image modeaif type == 'bmp' or type == 'png':mode = 'P' # image mode im.convert(mode).save(distDir+'/%d.'%cnt+type )cnt = cnt+1try:while 1:im.seek(im.tell()+1)im.convert(mode).save(distDir+'/%d.'%cnt+type)cnt = cnt+1except EOFError:pass # end of sequencewhite = (255,255,255)preIm = Image.open(distDir+'/%d.'%0+type).convert('RGB')size = preIm.sizeprePixs = preIm.load()for k in range (1,cnt):print '.',im = Image.open(distDir+'/%d.'%k+type).convert('RGB')pixs = im.load()for i in range(size[0]):for j in range(size[1]):if pixs[i,j] == white:pixs[i,j] = prePixs[i,j]preIm = imprePixs = preIm.load()im.convert(mode).save(distDir+'/%d.'%k+type)print '\n', filename, 'has been splited to directory: [',distDir,']'return cnt # 总帧数##############################################################
if __name__ == '__main__':frames = gif2images('source.gif',distDir='tmp',type='png')images = []for i in range(frames-1,-1,-1):images.append('tmp/%d.png'%i)images2gif(images,'save.gif', durations = 0.05)
参考: http://blog.csdn.net/hackjames/article/details/6950837
gif图片拆帧及合成[python]实现相关推荐
- Python实现.gif图片拆分为.png图片
Python实现.gif图片拆分为.png图片 实现效果展示: 未转化前的gif图片 经转化后: --------------------------------------------------- ...
- python--视频拆帧 帧合成视频流
1. 视频拆帧 #!/usr/bin/env python import cv2 numer = 18 cap=cv2.VideoCapture("/home/linux/work/pyth ...
- java,png,jpg,多张图片合成一个pdf,压缩图片,并且保证图片不失帧。
如何把图片合并成一个pdf,并且压缩图片大小至200以下,并且图片不失帧. /*** 合并图片转成pdf** @param inputImgUrls* @param outputFileName* @ ...
- 页面滚动时触发图片逐帧播放_如何在滚动效果上创建逐帧运动图像
页面滚动时触发图片逐帧播放 A step by step guide on how to create that dynamic image background you see everywhere ...
- 利用OpenCV-Python实现视频拆帧(组帧),也可以用于组合实现视频格式的转换
文章目录 前言 一.脚本运行依赖 二.参数解释与必需参数 1.视频拆帧 2.视频组帧 三.源代码 源码下载地址 前言 前一段时间写了一个简单的视频拆帧脚本,这次添加了一个将图片转为视频的组件,实现一个 ...
- excel图片变成代码_没错, Python杀死了Excel
在大家的印象里,想进入金融行业或者数据岗位,首先需要精通Excel.然而野村证券副首席数字官马修·汉普森在上周五的伦敦Quant Conference上发表讲话:"现在走进交易大厅,用Exc ...
- 如何用Python读取Excel中图片?又如何用Python往Excel中写入图片?
大家好,在使用Python进行办公自动化操作时,一定少不了与Excel表格的交互,我们通常是用pandas处理表格数据,但大多数情况下,都是读取表格中的数值进行分析. 那么你知道如何使用Python读 ...
- python表格中插入图片_运维(1)python操作excel插入图片
worksheet.insert_image() insert_image****(row, col, image[, options]) 在工作表单元格中插入一张图片. 参数: row(int) - ...
- 将GIF格式的图片逐帧转成PNG图片
背景介绍 我们在使用GIF格式的图片时,有需要将GIF逐帧按顺序转换为PNG静态图片的需求,例如:使用Pygame加载GIF资源需要先把GIF图片逐帧转换成PNG格式,再load到画布.类似的场景很有 ...
最新文章
- 分组表管理之保存分组表数据
- python编程基础知识体系_最新版 17 幅思维导图:Python 编程之核心知识体系
- ElasticSearch 5.5 离线环境的完整安装及配置详情,附kibana、ik插件配置及安装包下载路径...
- MPLS转发过程中涉及的相关概念—Vecloud微云
- b500k电位器引脚接法_可调电位器实物接线图及接线方法详解
- POJ - 2513 Colored Sticks(字典树+并查集+欧拉回路)
- ubuntu18.04新安装时Unable to locate package问题
- vue+node全栈移动商城【10】注册页面传值到node中间件
- Tomcat学习总结(13)—— Tomcat常用参数配置说明
- java使用itext开源包实现pdf文件合并,亲测可用,响应速度快的惊人
- redis删除不存在的key会报错吗_Redis哈希类型
- C语言代码实现最小二乘法线性拟合直线
- cat3 utp是不是网线_CAT网线知识
- Core Audio APIs 技术笔记二(麦克风音量和增强设置)
- JS new一个对象的过程
- DecisionTreeClassifier实例:Iris莺尾花分类
- 数据库连接池之自定义连接池(mysql)
- 计算机应用基础提问话题,10个开启新话题的过渡方法.docx-汇文网
- Oracle - 回滚段
- java 把文字转成图片_java文本文件转化为图片文件怎么弄?
热门文章
- WuThreat身份安全云-TVD每日漏洞情报-2022-12-23
- MATLAB软件复习
- 神秘的移动电商:服务三低人群
- 网友大宝(sodme)的来信
- 考研复试C语言微机原理,放福利,初试数模电,复试微机原理和C的进来看看
- PremiumSoft Navicat for MySQL 12.1.19中文版下载安装和注册机激活教程
- mysql各个版本的下载
- Python中类方法,静态方法,实例化方法
- 个人飞行器“iFLY”诞生,改变出行方式,人人都能飞?
- 2023年副业赚钱最快的方法,最后一个时代红利,你一定要抓住!