PIL : How to write array to image ???

Robert Kern robert.kern at gmail.com
Sat Oct 3 23:41:43 CEST 2009


Martin wrote:
> Dear group
> 
> I'm trying to use PIL to write an array (a NumPy array to be exact) to
> an image.
> Peace of cake, but it comes out looking strange.
> 
> I use the below mini code, that I wrote for the purpose. The print of
> a looks like expected:
> 
> [[ 200.  200.  200. ...,    0.    0.    0.]
>  [ 200.  200.  200. ...,    0.    0.    0.]
>  [ 200.  200.  200. ...,    0.    0.    0.]
>  ...,
>  [   0.    0.    0. ...,  200.  200.  200.]
>  [   0.    0.    0. ...,  200.  200.  200.]
>  [   0.    0.    0. ...,  200.  200.  200.]]
> 
> But the image looks nothing like that.
> 
> Please see the images on:
> http://hvidberg.net/Martin/temp/quat_col.png
> http://hvidberg.net/Martin/temp/quat_bw.png
> 
> or run the code to see them locally.
> 
> Please – what do I do wrong in the PIL part ???
> 
> :-? Martin
> 
> 
> 
> import numpy as np
> from PIL import Image
> from PIL import ImageOps
> 
> maxcol = 100
> maxrow = 100
> 
> a = np.zeros((maxcol,maxrow),float)
> 
> for i in range(maxcol):
>     for j in range(maxrow):
>         if (i<(maxcol/2) and j<(maxrow/2)) or (i>=(maxcol/2) and j>=
> (maxrow/2)):
>             a[i,j] = 200
>         else:
>             a[i,j] = 0
> 
> print a
> 
> pilImage = Image.fromarray(a,'RGB')

You are telling it the wrong mode information. If you want an RGB image, you 
need to give it a uint8 array with shape (height, width, 3). Exactly what are 
you trying to do? I can't infer that from your code.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list