[Numpy-discussion] how to convert btw rgb and pixel value

Stefan van der Walt stefan at sun.ac.za
Mon Nov 12 16:08:40 EST 2007


Since PIL Images now have array interfaces, it has become a lot
simpler.  The following should do the job:


from numpy import array
from PIL import Image

def imread(fname,flatten=False):
    """Return a copy of a PIL image as a numpy array.

    *Parameters*:
        im : PIL image
            Input image.
        flatten : bool
            If true, convert the output to grey-scale.

    *Returns*:
        img_array : ndarray
            The different colour bands/channels are stored in the
            third dimension, such that a grey-image is MxN, an
            RGB-image MxNx3 and an RGBA-image MxNx4.

    """
    im = Image.open(fname)
    if flatten:
        im = im.convert('F')
    return array(im)

Cheers
Stéfan

On Mon, Nov 05, 2007 at 12:58:45PM +0200, Nadav Horesh wrote:
> If the image is in the form of a standard image format (png, bmp, jpeg...) you
> can use the PIL library. png file can be read by pylab's imread function.
> 
>    Nadav.
> 
> On Sun, 2007-11-04 at 23:37 -0800, devnew at gmail.com wrote:
> 
>     hi
>     i wish to convert an rgb image into an array of double values..is
>     there a method for that in numpy?
>     also i want to create an array of doubles into corresponding rgb
>     tuples of an image
>     can anyone guide me?
>     dn



More information about the NumPy-Discussion mailing list