我在 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 行),假设这样可以解决问题。
图像很大,但我没有得到内存错误。
我在这个问题上卡住了很长一段时间,我只是不知道问题出在哪里。任何帮助将不胜感激。
最佳答案
尝试使用 resize()
方法的 resample
参数。
尽管根据提供的文档字符串,此参数是可选的:
resample – An optional resampling filter. This can be one of PIL.Image.NEAREST (use nearest neighbour), PIL.Image.BILINEAR (linear interpolation), PIL.Image.BICUBIC (cubic spline interpolation), or PIL.Image.LANCZOS (a high-quality downsampling filter). If omitted, or if the image has mode “1” or “P”, it is set PIL.Image.NEAREST.
我想明确指定它可能会有所帮助。至少它对我有帮助。
关于python - 调整图像大小时 PIL "ValueError: image has wrong mode",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38192992/