繁体   English   中英

调整图像大小时 PIL“ValueError:图像模式错误”

[英]PIL "ValueError: image has wrong mode" when resizing an image

我在 Blender 工作,所以我想使用在互联网上找到的凹凸贴图。 图像在这里 但是,当我尝试使用它时,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 行),假设这样可以解决问题。

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM