Pillow Image对象和numpy数组之间的转换会更改维度

问题描述 投票:23回答:3

我正在使用Pillow和numpy,但在Pillow Image对象和numpy数组之间进行转换时遇到问题。

当我执行以下代码时,结果很奇怪。

im = Image.open(os.path.join(self.img_path, ifname))
print im.size
in_data = np.asarray(im, dtype=np.uint8)
print in_data.shape

结果是

(1024, 768)
(768, 1024)

尺寸为何改变?

python arrays numpy python-imaging-library pillow
3个回答
16
投票

我可能是列专业,而numpy中的数组是行主要的

in_data = in_data.T来转置python数组

可能应该检查in_data与matplotlibimshow,以确保图片看起来正确。

但是你知道matplotlib有自己的加载函数,可以直接为你提供numpy数组吗?见:http://matplotlib.org/users/image_tutorial.html


5
投票

如果您的图像是灰度,请执行以下操作:

in_data = in_data.T

但是如果您正在使用rbg图像,则需要确保转置操作仅沿两个轴:

in_data = np.transpose(in_data, (1,0,2))

0
投票

实际上这是因为大多数图像库都提供了与numpy数组相比转换的图像。这是(我认为),因为你逐行写图像文件,所以第一个索引(比如x)是指行号(所以x是垂直轴),第二个索引(y)是指后续的像素line(所以y是横轴),这与我们的日常坐标感相反。

如果你想正确处理它,你需要记住写:

image = library.LoadImage(path)
array = (library.FromImageToNumpyArray(image)).T

因此:

image = library.FromNumpyArrayToImage(array.T)
library.WriteImage(image, path)

这也适用于3D图像。但我不承诺这是所有图像库的情况 - 只是我使用过的这些。

© www.soinside.com 2019 - 2024. All rights reserved.