简体   繁体   English

使用NumPy交换数组尺寸

[英]Swapping array dimensions with NumPy

When I load an image with PIL and convert it into a NumPy array: 当我使用PIL加载图像并将其转换为NumPy数组时:

image = Image.open("myimage.png")
pixels = np.asarray(image)

The data is stored as [x][y][channel]. 数据存储为[x] [y] [channel]。 Ie, the value of pixels[3, 5, 0] will be the the (3, 5) pixel, and the red component of that pixel. 即,pixels [3,5,0]的值将是(3,5)像素,以及该像素的红色分量。

However, I am using a library which requires the image to be in the format [channel][x][y]. 但是,我使用的库要求图像的格式为[channel] [x] [y]。 Therefore, I am wondering how I can do this conversion? 因此,我想知道如何进行此转换?

I know that NumPy has a reshape function, but this doesn't actually allow you to "swap" over the dimensions as I want. 我知道NumPy具有reshape功能,但这实际上并不允许您按照我的意愿“交换”尺寸。

Any help? 有什么帮助吗? Thanks! 谢谢!

In order to get the dimensions in the order that you want, you could use the transpose method as follows: 为了按所需顺序获取尺寸,可以使用如下的transpose方法:

image = Image.open("myimage.png")
pixels = np.asarray(image).transpose(2,0,1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM