值误差:尺寸太多:3> 2

时间:2016-04-25 13:08:31

标签: python arrays scipy python-imaging-library

我试图用scipy调整图像大小,一切似乎工作正常,直到我尝试保存图像。当我尝试保存图像时,我会收到标题中可以看到的错误。完整的追溯可在下面找到。

import numpy as np
import scipy.misc
from PIL import Image

image_path = "img0.jpg"


def load_image(img_path):
    img = Image.open(img_path)
    img.load()
    data = np.asarray(img, dtype="int32")
    return data


def save_image(npdata, outfilename):
    img = Image.fromarray(np.asarray(np.clip(npdata, 0, 255), dtype="uint8"), "L")
    img.save(outfilename)

array_image = load_image(image_path)

array_resized_image = scipy.misc.imresize(array_image, (320, 240), interp='nearest', mode=None)

save_image(array_resized_image, "i1.jpg")

错误的完整追溯:

Traceback (most recent call last):
  File "D:/Python/Playground/resize image with scipy.py", line 26, in <module>
    save_image(array_resized_image, "i1.jpg")
  File "D:/Python/Playground/resize image with scipy.py", line 16, in save_image
    img = Image.fromarray(np.asarray(np.clip(npdata, 0, 255), dtype="uint8"), "L")
  File "C:\Anaconda2\lib\site-packages\PIL\Image.py", line 2154, in fromarray
    raise ValueError("Too many dimensions: %d > %d." % (ndim, ndmax))
ValueError: Too many dimensions: 3 > 2.

2 个答案:

答案 0 :(得分:2)

在执行fromarray(...'L')之前,是否需要将其转换为二维数组?

你可以使用scipy函数,或者实际上更快,将RGB乘以因子。喜欢这个

npdata = (npdata[:,:,:3] * [0.2989, 0.5870, 0.1140]).sum(axis=2)

答案 1 :(得分:2)

array_resized_image的形状为(320, 240, 3) - 三维,因为红色,绿色和蓝色组件以这种方式存储。您可以使用scipy.misc.imreadscipy.misc.imsave来更轻松地处理文件加载和存储,因此您的示例可归结为:

import scipy.misc

image_path = "img0.jpg"

array_image = scipy.misc.imread(image_path)
array_resized_image = scipy.misc.imresize(array_image, (320, 240), interp='nearest', mode=None)
scipy.misc.imsave("i1.jpg", array_resized_image)