【发布时间】:2012-05-03 09:20:13
【问题描述】:
我尝试使用 Python 图像库将 gif 转换为单个图像, 但它会导致奇怪的帧
输入的 gif 是:
Source Image http://longcat.de/gif_example.gif
在我的第一次尝试中,我尝试将带有 Image.new 的图像转换为 RGB 图像,以 255,255,255 作为白色背景 - 与任何其他图像一样 我在互联网上找到的示例:
def processImage( infile ):
try:
im = Image.open( infile )
except IOError:
print "Cant load", infile
sys.exit(1)
i = 0
try:
while 1:
background = Image.new("RGB", im.size, (255, 255, 255))
background.paste(im)
background.save('foo'+str(i)+'.jpg', 'JPEG', quality=80)
i += 1
im.seek( im.tell() + 1 )
except EOFError:
pass # end of sequence
但它会导致奇怪的输出文件:
Example #1 http://longcat.de/gif_example1.jpg
我的第二次尝试是,先将 gif 转换为 RGBA,然后使用 它的透明蒙版,使透明部分变白:
def processImage( infile ):
try:
im = Image.open( infile )
except IOError:
print "Cant load", infile
sys.exit(1)
i = 0
try:
while 1:
im2 = im.convert('RGBA')
im2.load()
background = Image.new("RGB", im2.size, (255, 255, 255))
background.paste(im2, mask = im2.split()[3] )
background.save('foo'+str(i)+'.jpg', 'JPEG', quality=80)
i += 1
im.seek( im.tell() + 1 )
except EOFError:
pass # end of sequence
导致如下输出:
Example #2 http://longcat.de/gif_example2.jpg
与第一次尝试相比的优势在于,第一帧看起来不错 但正如你所看到的,其余的都坏了
接下来我应该尝试什么?
编辑:
我认为我离解决方案更近了
Example #3 http://longcat.de/gif_example3.png
我不得不将第一张图片的调色板用于其他图片, 并将其与前一帧合并(对于使用 差异图像)
def processImage( infile ):
try:
im = Image.open( infile )
except IOError:
print "Cant load", infile
sys.exit(1)
i = 0
size = im.size
lastframe = im.convert('RGBA')
mypalette = im.getpalette()
try:
while 1:
im2 = im.copy()
im2.putpalette( mypalette )
background = Image.new("RGB", size, (255,255,255))
background.paste( lastframe )
background.paste( im2 )
background.save('foo'+str(i)+'.png', 'PNG', quality=80)
lastframe = background
i += 1
im.seek( im.tell() + 1 )
except EOFError:
pass # end of sequence
但我其实不知道,为什么我的透明度是黑色的,而不是白色的 即使我修改调色板(将透明度通道更改为白色) 或者使用透明蒙版,背景还是黑色的
【问题讨论】:
标签: python image-processing python-imaging-library gif jpeg