Convert Between Numerical Arrays and PIL Image Objects

October 1998 | Fredrik Lundh

This module provides two helper functions that allow you to convert between Numerical Python (dead link) arrays and PIL images. The fromstring/tostring approach may look a bit crude, but experiments (by others) indicate that the result is about as fast as it can get, on most modern platforms.

# convert between numerical arrays and PIL image memories
# fredrik lundh, october 1998

import Numeric, Image

def image2array(im):
    if im.mode not in ("L", "F"):
        raise ValueError, "can only convert single-layer images"
    if im.mode == "L":
        a = Numeric.fromstring(im.tostring(), Numeric.UnsignedInt8)
        a = Numeric.fromstring(im.tostring(), Numeric.Float32)
    a.shape = im.size[1], im.size[0]
    return a

def array2image(a):
    if a.typecode() == Numeric.UnsignedInt8:
        mode = "L"
    elif a.typecode() == Numeric.Float32:
        mode = "F"
        raise ValueError, "unsupported image mode"
    return Image.fromstring(mode, (a.shape[1], a.shape[0]), a.tostring())

See Also

Ed Jones: Python Utilities and Packages. Includes PyCV and other modules (dead link) that can be used to connect PIL to NumPy and other libraries.


A Django site. rendered by a django application. hosted by webfaction.