Python 有没有办法用PIL读取截短的gif?

Python 有没有办法用PIL读取截短的gif?,python,python-imaging-library,Python,Python Imaging Library,我正在尝试用Python读取GIF图像,它似乎可以很好地用于浏览器,但不能用于PIL。使用下面的代码 from PIL import Image im = Image.open('flow.gif') im = im.convert('RGB') 我得到了下面的回溯 --------------------------------------------------------------------------- IOError

我正在尝试用Python读取GIF图像,它似乎可以很好地用于浏览器,但不能用于PIL。使用下面的代码

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)
---------------------------------------------------------------------------
IOError回溯(最近一次呼叫最后一次)
在()
1 im=Image.open('flow.gif')
---->2 im=im.convert('RGB')
/转换中的Users/../site packages/PIL/Image.pyc(自我、模式、数据、抖动、调色板、颜色)
672返回self.copy()
673
-->674 self.load()
675
676如果数据:
/Users/../site packages/PIL/ImageFile.pyc正在加载(self)
218休息
219其他:
-->220 raise IOError(“图像文件被截断(%d字节未处理)”%len(b))
221
222 b=b+s
IOError:图像文件被截断(未处理241字节)
图为:


我尝试使用ImageMagick将图像转换为另一种格式,但ImageMagick也不喜欢。如果我在OSX中使用预览,它在读取图像时没有问题,就像浏览器一样。看起来这些应用程序可以处理这些问题,但不能处理PIL。有什么解决方法或解决方案吗?

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')
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

只需在代码块之前添加以下内容:

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')
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
我根据你提供的照片测试了这一点,我能够毫无问题地处理图像


编辑:这看起来对PIL与枕头捆绑的版本(“pip安装枕头”)有帮助,但对于默认安装的PIL可能不起作用

如果使用gimp/浏览器重新保存它不起作用,您可以尝试
枕头
。我尝试了枕头,但也出现了一个错误。我有点惊讶,没有Python软件包可以解析这样的GIF图像,而Preview、Chrome和许多其他应用程序却没有抱怨。显然,它们是针对此类事件进行优化的。除非您有大量损坏的GIF,否则请将其保存为有效格式。