简体   繁体   English

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

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

I am working in Blender and so I wanted to use a bump map I found on the internet.我在 Blender 工作,所以我想使用在互联网上找到的凹凸贴图。 The image is here .图像在这里 However, when I tried to use it, Blender crashed.但是,当我尝试使用它时,Blender 崩溃了。 I am assuming that happened because of the size of the image.我假设这是由于图像的大小而发生的。 That's why I wanted to create a simple script that would resize an image.这就是为什么我想创建一个可以调整图像大小的简单脚本。

This is my script:这是我的脚本:

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)

When I run the script I get the following error:当我运行脚本时,我收到以下错误:

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

As you can see from the script, I already tried changing the mode to "RGB" (line 14), assuming that would fix the problem.正如您从脚本中看到的那样,我已经尝试将模式更改为“RGB”(第 14 行),假设这样可以解决问题。

The image is quite large but I don't get the memory error.图像很大,但我没有收到内存错误。

I am stuck on that problem for quite a while and I just don't know what the problem is.我被这个问题困扰了很长一段时间,我只是不知道问题是什么。 Any help would be appreciated.任何帮助,将不胜感激。

Try to play with resample parameter of resize() method.尝试使用resize()方法的resample参数。 Although this parameter is optional according to the provided docstring:尽管根据提供的文档字符串,此参数是可选的:

resample – An optional resampling filter. resample - 一个可选的重采样过滤器。 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).这可以是 PIL.Image.NEAREST(使用最近邻)、PIL.Image.BILINEAR(线性插值)、PIL.Image.BICUBIC(三次样条插值)或 PIL.Image.LANCZOS(高质量下采样滤波器)之一)。 If omitted, or if the image has mode “1” or “P”, it is set PIL.Image.NEAREST.如果省略,或者图像的模式为“1”或“P”,则设置为 PIL.Image.NEAREST。

I guess explicitly specifying it may help.我想明确指定它可能会有所帮助。 At least it helped me.至少它帮助了我。

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

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