Python, NumPy and 16-bit tiff files

Dick Madden madden at ihes.fr
Mon Feb 3 12:44:56 EST 2003


Marcin Swiatek wrote:

> Hi,
>
> I have got quite a number of 16 bit images that I need to analyze. I
> thought that Python and NumPy would serve me well - as they always did
> with other number crunching. However, I do not know, how to bring
> these images (16-bit TIFFs) in. PIL doesn't seem to cut it - as a
> matter of fact the PIL-makers are quite explicit about that.
>
> Do you know of any library that I could use to load these images and
> convert them into Numeric matrices?
>
> Regards,
>
> Marcin

Hi,

    Happens I'm doing exactly the same thing. Turns out PIL will read 16 
bit TIFFs (at least mine). Go to the TiffImagePlugin.py file in the PIL
site-package and add the line:

     (1, 1, (16,), ()): ("I;16", "I;16"),

just before the line    (1, 2, (16,), ()): ("I;16", "I;16"), in the 
OPEN_INFO definition. This should let you read the tiffs. (I'm a little 
vague on what it actually does...).

    For converting the images to arrays, I found the following someplace.

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

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

Ciao, Dick






More information about the Python-list mailing list