[Numpy-discussion] asarray() and PIL

Christopher Barker Chris.Barker@noaa....
Wed May 27 11:43:55 CDT 2009

cp wrote:
>>> arr=asarray(img)
>>> arr.shape
>>> (1600,1900,3)
>> No, it means that you have 1600 rows, 1900 columns and 3 colour channels.
> According to scipy documentation at
> http://pages.physics.cornell.edu/~myers/teaching/ComputationalMethods/python/arrays.html
> you are right.
> In this case I import numpy where according to
> http://www.scipy.org/Tentative_NumPy_Tutorial and the Printing Arrays paragraph
> (also in http://www.scipy.org/Numpy_Example_List#reshape reshape example) the
> first number is the layer, the second the rows and the last the columns.
> Are all the above valid or am I missing something?

I'm not sure what part of those docs you're referring to -- but they are 
probably both right. What you are missing is that numpy doesn't define 
for you what the axis mean, they just are:

the zeroth axis is of length 1600 elements
the first  axis is of length 1900 elements
the second axis is of length    3 elements

what they represent is up to your application. In the case of importing 
from PIL, it is (height, width, rgb) (I think height and width get 
swapped due to how memory is laid out in PIL vs numpy)

by default, numpy arrays are stored and worked with in C-array order, so 
that array layout has the pixels together in memory as rgb triples. 
Depending on what you are doing you may not want that. You can work with 
them any way you want:

sub_region = arr[r1:r2, c1:c2, :]

all_red = arr[:,:,0]

but if you tend to work with all the red, or all the blue, etc, then it 
might be easier to re-arrange it to:

(rgb, height, width)

If you google a bit, you'll find various notes about working with image 
data in numpy.



Christopher Barker, Ph.D.

Emergency Response Division
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception


More information about the Numpy-discussion mailing list