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

Jon*_*Kim 23 python arrays numpy python-imaging-library pillow

我正在使用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
Run Code Online (Sandbox Code Playgroud)

结果是

(1024, 768)
(768, 1024)
Run Code Online (Sandbox Code Playgroud)

尺寸为何改变?

prg*_*gao 16

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

in_data = in_data.T转置python数组

可能应该用matplotlib's 检查in_data以imshow确保图片看起来正确.

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


小智 5

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

in_data = in_data.T
Run Code Online (Sandbox Code Playgroud)

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

in_data = np.transpose(in_data, (1,0,2))
Run Code Online (Sandbox Code Playgroud)