【问题标题】:PIL "ValueError: image has wrong mode" when resizing an image调整图像大小时,PIL“ValueError:图像模式错误”
【发布时间】:2016-11-06 16:11:07
【问题描述】:

我在 Blender 工作,所以我想使用在互联网上找到的凹凸贴图。 图片是here。但是,当我尝试使用它时,Blender 崩溃了。我假设这是由于图像的大小而发生的。这就是为什么我想创建一个可以调整图像大小的简单脚本。

这是我的脚本:

from PIL import Image
from math import sqrt

path = raw_input("Enter file path: ")

Image.warnings.simplefilter('ignore', Image.DecompressionBombWarning)
img = Image.open(path)
size = img.size
pixelsize = size[0] * size[1]
print "Current pixel size:", pixelsize

maxsize = input("Enter maximum pixel size: ")

img = img.convert(mode="RGB")
square1 = sqrt(pixelsize)
ratio = (size[0] / square1, size[1] / square1)
square2 = sqrt(maxsize)
newsize = (int(round(maxsize * ratio[0])), int(round(maxsize * ratio[1])))
img = img.resize(newsize)

oldname = path.split("/")[-1]
newname = "SMALLER_" + oldname

img.save(newname)

当我运行脚本时,出现以下错误:

Traceback (most recent call last):
  File "C:/Users/*****/Desktop/smaller/makeImageSmaller.py", line 19, in <module>
    img = img.resize(newsize)
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 1550, in resize
    return self._new(self.im.resize(size, resample))
ValueError: image has wrong mode

从脚本中可以看出,我已经尝试将模式更改为“RGB”(第 14 行),假设这样可以解决问题。

图像很大,但我没有收到内存错误。

我被这个问题困扰了很长一段时间,我只是不知道问题是什么。任何帮助将不胜感激。

【问题讨论】:

标签: python image python-imaging-library image-resizing


【解决方案1】:

尝试使用resize() 方法的resample 参数。 尽管根据提供的文档字符串,此参数是可选的:

resample – 一个可选的重采样过滤器。这可以是其中之一 PIL.Image.NEAREST(使用最近邻),PIL.Image.BILINEAR(线性 插值),PIL.Image.BICUBIC(三次样条插值),或 PIL.Image.LANCZOS(一个高质量的下采样过滤器)。如果省略,或 如果图像的模式为“1”或“P”,则设置为 PIL.Image.NEAREST。

我想明确指定它可能会有所帮助。至少它帮助了我。

【讨论】:

    猜你喜欢
    • 2012-12-01
    • 2017-04-01
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多