Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to view an RGB image with pylab

I'm trying to view an 32x32 pixel RGB image in CIFAR-10 format. It's a numpy array where pixel values (uint8) are arranged as follows: "The first 1024 bytes are the red channel values, the next 1024 the green, and the final 1024 the blue. The values are stored in row-major order, so the first 32 bytes are the red channel values of the first row of the image."

Thus, the original image shape is:

numpy.shape(image)
(3072L,)

I reshape it like this:

im = numpy.reshape(image, (32,32,3))

However, when I try

imshow(im)

in iPython console, I see 3 by 3 tiles of the original image: enter image description here

I expected to see a single image of a car instead. I saw this question here, but I'm not sure what are they doing there, and if it's relevant to my situation.

like image 287
MichaelSB Avatar asked Jan 17 '15 23:01

MichaelSB


2 Answers

I know it's been a while since the question was posted but I want to correct Oliver's answer. If you order by Fortran, the image is inverted and rotated by 90 degrees CCW.

You can still train on this data of course if you format all of your images this way. But to prevent you from going insane, you should do the following:

im = c.reshape(3,32,32).transpose(1,2,0)

What you are doing is first reshaping the matrix using the default format which gets you RGB in the first dimension and then rows and columns in the other two dimensions. Then you are shuffling the dimensions so that the first dimension in the original (RGB, indexed at 0) is switched to the third dimension and the second and third dimensions each move up by 1.

Hope that this helped.

like image 159
Tony Avatar answered Nov 06 '22 15:11

Tony


Try changing the order. By default, it is C-contiguous (which is in fact row-major), but for matplotlib, you'll want the red channel values in [:,:,0]. That means you should read that data in in Fortran order so that it first fills the "columns" (in this 3D context).

im = numpy.reshape(c, (32,32,3), order='F')
like image 45
Oliver W. Avatar answered Nov 06 '22 14:11

Oliver W.