簡體   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