Skip to main content
 首页 » 编程设计

python之在我将 2D 灰度 PIL 图像转换为 1D numpy 数组后,获得 2D numpy 数组(图像/矩阵)的最平滑方法是什么

2025年05月04日6EasonJim

我的代码是这样的:

img = Image.open(path) 
pix = np.asarray(img) 
# i tried to access an (x,y) pixel and found the array was one dimensional 
print str(float(pix[1,1])), "\t", 

我需要打乱一维数组,使其成为二维数组,以便我可以访问 (x,y) 像素。执行此操作最顺利的方法是什么?

我收到上述错误:

IndexError: too many indices for array 

编辑:

下面是执行上述代码后从终端收集的一些信息。 np.asarray() 显然是在做一些事情,关于图像维度的信息仍然包含在 ndarray pix 中。 -- array(<PIL.TiffImagePlugin.TiffImageFile image mode=I;16 size=1280x1080 at 0x110CA9F38>, dtype=object) .

>>> img 
<PIL.TiffImagePlugin.TiffImageFile image mode=I;16 size=1280x1080 at 0x110CA9F38> 
>>> pix 
array(<PIL.TiffImagePlugin.TiffImageFile image mode=I;16 size=1280x1080 at 0x110CA9F38>, dtype=object) 
>>> type(img) 
<type 'instance'> 
>>> type(pix) 
<type 'numpy.ndarray'> 
>>> img.size 
(1280, 1080) 
>>> pix.size 
1 

请您参考如下方法:

如果你可以使用scipy:

from scipy import ndimage 
image = ndimage.imread('image.png') 
image.shape