2013-08-29 55 views
1

我正尝试在Python中读取GIF图像,该图像似乎可以在浏览器中正常工作,但与PIL无关。下面有没有办法用PIL读取截断的gif?

from PIL import Image 

im = Image.open('flow.gif') 
im = im.convert('RGB') 

我得到以下回溯

--------------------------------------------------------------------------- 
IOError         Traceback (most recent call last) 
<ipython-input-35-6f71a00ad83b> in <module>() 
     1 im = Image.open('flow.gif') 
----> 2 im = im.convert('RGB') 

/Users/.../site-packages/PIL/Image.pyc in convert(self, mode, data, dither, palette, colors) 
    672     return self.copy() 
    673 
--> 674   self.load() 
    675 
    676   if data: 

/Users/.../site-packages/PIL/ImageFile.pyc in load(self) 
    218        break 
    219       else: 
--> 220        raise IOError("image file is truncated (%d bytes not processed)" % len(b)) 
    221 
    222      b = b + s 

IOError: image file is truncated (241 bytes not processed) 

这里代码的图像:problematic gif image

我试图用ImageMagick的将图像转换为另一种格式,但ImageMagick的不喜欢它也是。如果我在OSX中使用“预览”,那么阅读图像(如浏览器)就没有问题。看起来应用程序可以处理这些问题,但不是PIL。有关解决方法或解决方案的任何想法?

+0

如果重新保存它与GIMP /浏览器没有按”工作工作,你可以尝试'枕头'。 – ninMonkey

+0

我试过枕头,也有错误。我有点惊讶,没有可以像这样解析GIF图像的Python包,而Preview,Chrome和其他许多应用程序不会抱怨。显然,它们针对这些事件进行了优化。 – ebressert

+0

除非你有一大批破碎的GIF,只需将其保存为有效的格式即可。 – ninMonkey

回答

1

opencv可以处理gif。它将它们视为像任何其他视频或流一样的框架容器。 如果你安装了它,你可以做到以下几点:

import cv2 
from PIL import Image 
gif = cv2.VideoCapture('file.gif') 
ret,frame = gif.read() # ret=True if it finds a frame else False. Since your gif contains only one frame, the next read() will give you ret=False 
img = Image.fromarray(frame) 
img = img.convert('RGB') 
4

某处你的代码块之前,只需添加以下内容:

from PIL import ImageFile 
ImageFile.LOAD_TRUNCATED_IMAGES = True 

我测试了针对您所提供的照片,我能够在没有任何问题的情况下处理图像。

编辑:它看起来像这样有助于为PIL与枕头捆绑(“PIP安装枕头”)的版本,但不得用于PIL的默认安装

相关问题