打开大tiff文件时Pillow的Image.open()MemoryError

时间:2015-06-10 21:08:01

标签: python image tiff pillow

我正在编写一个将在服务器上运行的python脚本,并将调整图像大小(即Indesign链接)。一切正常,除非我试图打开更大的tiff文件(800 MB)。

我正在使用 Pillow的Image.open()来调整大小,但我收到 MemoryError 错误。我尝试使用其他库,如ImageMagick和tifffile,结果相同。我可以将它拆分成更小的块,调整它们然后组合它们,但我不知道如何在不先打开文件的情况下这样做。

我进行了广泛的搜索,但找不到对我来说似乎合适的解决方案。我也在观察内存消耗,它看起来并不高。可以说我完全迷失了。

整个过程如下:

Traceback (most recent call last):
  File "app.py", line 87, in <module>
    convert()
  File "X:\Development\Python\zipper\converter.py", line 112, in convert
    if saveAsJPEG(file, name + ".jpg"): converted_images = updateCounter(all_images, converted_images)
  File "X:\Development\Python\zipper\converter.py", line 37, in saveAsJPEG
    print Image.open(a).size
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 2266, in open
    im = factory(fp, filename)
  File "C:\Python27\lib\site-packages\PIL\ImageFile.py", line 97, in __init__
    self._open()
  File "C:\Python27\lib\site-packages\PIL\TiffImagePlugin.py", line 637, in _open
    self._seek(0)
  File "C:\Python27\lib\site-packages\PIL\TiffImagePlugin.py", line 672, in _seek
    self.tag.load(self.fp)
  File "C:\Python27\lib\site-packages\PIL\TiffImagePlugin.py", line 458, in load
    data = ImageFile._safe_read(fp, size)
  File "C:\Python27\lib\site-packages\PIL\ImageFile.py", line 521, in _safe_read
    block = fp.read(min(size, SAFEBLOCK))
MemoryError

谢谢大家的帮助!

---编辑

这是抛出错误的代码

def saveAsJPEG(file, newfile):
    print "\nopening:", file
    try:
        with Image.open(file) as im:
            if not im.size[0] < size[0] or im.size[1] < size[1]:
                new_im = im.resize(size, Image.ANTIALIAS)
                new_im.save(newfile, 'JPEG', quality=100, dpi=(72, 72))

                # Force a memory dump.  Otherwise memory will get cluttered up -> I am not sure if this is necessary as it doesn't seem to do anything. 
                del im
                del new_im
                collect()
                return True
    except:
        print "image is too big -> try something else. But what?"
        # this line below throws error (MemoryError). It was the same without try-except part before.
        Image.open(file)

该函数用于for循环,其中“images”是完整文件路径的数组(列表)(X:\ path \ to \ my \ image.tiff)

for file in images:
    #gets extension
    name = basename(splitext(file)[0])
    ext = splitext(file)[1]

    # check for extension type and run appropriate function
    if ext == '.jpg' or ext == '.jpeg' or ext == '.tif' or ext == '.tiff':
        if saveAsJPEG(file, name + ".jpg"): converted_images = updateCounter(all_images, converted_images)

    del file, name, ext

0 个答案:

没有答案