简体   繁体   中英

Swapping array dimensions with NumPy

When I load an image with PIL and convert it into a NumPy array:

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

The data is stored as [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.

However, I am using a library which requires the image to be in the format [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.

Any help? Thanks!

In order to get the dimensions in the order that you want, you could use the transpose method as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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