[SciPy-User] Trying to use PIL and numpy

Andy Fraser afraser@lanl....
Mon Jan 11 17:47:46 CST 2010

>>>>> "AJ" ==   <alan@ajackson.org> writes:

    AJ> I'm having some issues trying to use PIL and numpy (for the
    AJ> first time).  It's probably something simple, it usually is.

I'm learning to work with images too.  I started with PIL.Image for
looking at images, but now I am moving towards pyFltk and ImageMagick.

I find it difficult to keep track of how bits in arrays get mapped to
pixels on the screen.  I end up with lines like 

A = A.transpose((1,0,2))[::-1,:,:]

in my code.  Here is a utility that depends on PIL that I use to look
at data:

from PIL import Image # /usr/share/pyshared/PIL/Image.py
def display(A,msg='Default msg for displaying an array', MAX=None):
    import tempfile, os
    if A.ndim == 3:
        if A.shape[0] == 3:  # This is gdal format
            A = A.transpose((1,2,0))
            A = A.transpose((1,0,2))[::-1,:,:]
    if A.dtype == numpy.dtype(numpy.bool):
        A = numpy.array(A*255,numpy.uint8)
    if A.dtype != numpy.dtype(numpy.uint8):
        if MAX == None:
            MAX = A.max(0).max(0)
        MIN = A.min(0).min(0)
        scale = 1.0/(MAX-MIN)
        T = (A-MIN)*scale
        A = numpy.array(T*256,numpy.uint8)
    Name = tempfile.mktemp(dir='temp')
    image = Image.fromarray(A)
    #os.system('eog %s'%Name)    # eog is eye of gnome
    os.system('display %s'%Name) # display from ImageMagick
    print msg
    os.system('rm %s'%Name)

More information about the SciPy-User mailing list