调整图像大小时,PIL“ValueError:image has error mode”(图像模式错误)

2024-09-29 00:23:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在搅拌机工作,所以我想用我在网上找到的凹凸图。 图像是here。然而,当我试着用它时,搅拌机坏了。我想这是因为图像的大小。这就是为什么我想创建一个简单的脚本来调整图像的大小。在

这是我的剧本:

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)

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

^{pr2}$

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

图像相当大,但我没有记错。在

我在那个问题上纠结了一段时间,只是不知道问题出在哪里。任何帮助都将不胜感激。在


Tags: pathfrom图像imageimport脚本imginput
1条回答
网友
1楼 · 发布于 2024-09-29 00:23:27

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

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.

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

相关问题 更多 >