We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

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 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
#
# fredrik@pythonware.com
# http://www.pythonware.com
#

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)
    else:
        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"
    else:
        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 that can be used to connect PIL to NumPy and other libraries.