[Image-SIG] help for conversion of NUMARRAY to PIL object

Bob Klimek klimek at grc.nasa.gov
Fri Sep 16 14:19:25 CEST 2005

Zhenglong Li wrote:

>Hi, Fredrik,
>	Thank you very much for your help. But there still exists a problem 
>that the code cann't deal with 3-channel RGB image. If I want to read a 
>len*width*3 matrix from PIL object into NumArray, and vice versa, what 
>should I do?
Try this.

import numarray as N
import Image

screenLevels = 255.0 # we have 8 bit video cards

def image2array(im, convertType='UInt8'):
    Convert PIL image to Numarray array
    if im.mode == "L":
        a = N.fromstring(im.tostring(), N.UInt8)
        a = N.reshape(a, (im.size[1], im.size[0]))
        #a.shape = (im.size[1], im.size[0], 1)  # alternate way
    elif (im.mode=='RGB'):
        a = N.fromstring(im.tostring(), N.UInt8)
        a.shape = (im.size[1], im.size[0], 3)
        raise ValueError, im.mode+" mode not considered"

    if convertType == 'Float32':
        a = a.astype(N.Float32)
    return a

def array2image(a):
    Converts array object (numarray) to image object (PIL).
    h, w = a.shape[:2]
    int32 = N.Int32
    uint32 = N.UInt32
    float32 = N.Float32
    float64 = N.Float64

    if a.type()==int32 or a.type()==uint32 or a.type()==float32 or 
        a = a.astype(N.UInt8) # convert to 8-bit
    if len(a.shape)==3:
        if a.shape[2]==3:  # a.shape == (y, x, 3)
            r = Image.fromstring("L", (w, h), a[:,:,0].tostring())
            g = Image.fromstring("L", (w, h), a[:,:,1].tostring())
            b = Image.fromstring("L", (w, h), a[:,:,2].tostring())
            return Image.merge("RGB", (r,g,b))
        elif a.shape[2]==1:  # a.shape == (y, x, 1)
            return Image.fromstring("L", (w, h), a.tostring())
    elif len(a.shape)==2:  # a.shape == (y, x)
        return Image.fromstring("L", (w, h), a.tostring())
        raise ValueError, "unsupported image mode"


More information about the Image-SIG mailing list