[Image-SIG] PIL vs Numpy in raster calculations

Christopher Barker Chris.Barker at noaa.gov
Wed May 27 19:29:16 CEST 2009


cp wrote:
>> image_array.reshape(-1,3).mean(axis=0)
>> what that does is reshape (without copying) the array into WxHx3 array
> 
> I have just one question considering importing the PIL image with asarray.
> Suppose my initial image is an RGB image with 1600 pixels height and 1900 width.
> 
>>>> img.size
> (1900,1600)
>>>> arr=asarray(img)
>>>> arr.shape
> (1600,1900,3)
> 
> In numpy syntax I would expect the last one to be (3,1900,1600). Now the
> returned array seems to have 1600 layers and not one for each color channel,
> leading to the reshape function you propose. Any idea why is that?

it looks like you've followed up on the lumpy list, but:

I misspoke a bit above:

image_array.reshape(-1,3)

means: "make this a 2-d array, making the first dimension whatever it 
needs to be so that the second dimension is three". In this case, that 
flattens out the width and height, while keeping the color separate, 
which I think is what you wanted -- the mean of each of red, green and blue.

from the reshape doc string:

reshaped_array : disarrays
         This will be a new view object if possible; otherwise, it will
         be a copy.


as your array was created from a PEEL image, it may need to make a copy 
to do this -- I'm not sure.

You might try the slice method I proposed -- if it can prevent a data 
copy, the extra loop may be worth it.

IIUC, PIL and numpy don't share exactly the same data model, so you may 
have to make a memory copy to go from one to the other -- that may the 
source of your performance decrease.

If you really want to know, you could profile the code doing one step at 
a time (not the mean, for instance) to see where the time is going.

-Chris




-- 
Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov


More information about the Image-SIG mailing list