Unable to reshape numpy array to RGB image

Viewed 833

I have an numpy array which is of all images from CIFAR10 dataset: (50000, 3072)

I am taking a single array out of it, its shape is (3072,) then am trying to convert it to RGB image by doing .reshape(32, 32, 3)

But when I pass it to plt.show() it shows something likeenter image description here

I am not sure why it is not showing the image correctly, I also tried .reshape(3, 32, 32) but it gives TypeError: Invalid shape (3, 32, 32) for image data while plotting

How do I reshape it correctly?

1 Answers

You should try np.swapaxes() to get valid shape for plt.imshow() to accept.

import numpy as np
dd = np.array([1]*3072).reshape(3, 32, 32)
dd1 = np.swapaxes(dd, 0, 2)

Try plt.imshow(dd1) to see what happens. (use your own data) :p

First of all, you should reshape using (3, 32, 32), this is determine by order of your data.

Then you have to display the reshape image, but plt.imshow() only accepts array with the shape (M, N) or (M, N, 3) or (M, N, 4), so you have to swap axes now as the reshaped data is (3, 32, 32). Details see plt.imshow and here

Related