0

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]. I.e., 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!

2
  • You could use the transpose method as opposed to the reshape method Commented Feb 2, 2017 at 17:09
  • There's swapaxes, rollaxis, and transpose. All of them allow you to permute axes in one way or another. Commented Feb 2, 2017 at 17:10

1 Answer 1

7

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.