SPIDER files and the Python Imaging Library

Back

Displaying images with Tkinter

The Python Imaging Library (PIL), adds image processing capabilities to Python. The library provides support for many popular image file formats (tif, gif, jpeg , bmp, png, and others), including SPIDER. Python Imaging-1.1.5 can read SPIDER formats; Imaging-1.1.6 can read/write SPIDER images, and can handle SPIDER image stacks. The library has general image processing functions for enhancement and filtering, simple transformations, drawing, and obtaining some statistics.

PIL provides image processing, but it cannot display images. For that, you need a graphics library, such as Tkinter.

The following lines of Python

% python
Python 2.3.3 (#9, May 25 2004, 10:53:39) [C] on irix6
>>> import Image
>>> im = Image.open('slice001.hrs')
>>> im.format
'SPIDER'
>>> im.getextrema()
(-2.59827, 1.55803)
>>> def neg1k(i): return i * -1000
... 
>>> im = im.point(neg1k)
>>> im.getextrema()
(-1558.034667, 2598.27441)
>>> im = im.transpose(Image.FLIP_LEFT_RIGHT)
>>> im.save('newimage.hrs', format='SPIDER')

Because it handles a variety of common formats, Image can be used to convert SPIDER images. Although save can determine the output format from the file extension, since SPIDER files can have any extension, the format must be specified explicitly. When SPIDER images are read by Image, they retain their floating point values. SPIDER files have a special convenience function, convert2byte, which rescales the values from 0..255. This rescale operation should be applied before any format conversion.
>>> bim = Image.open('newimage.hrs').convert2byte()  # read SPIDER image
>>> bim.save('newimage.gif')  # save it in gif format for our web page

Code for a simple image conversion program.

Note: for converting between the specialized formats used by the 3D electron microscope community, see EM2EM.
You can also convert between PIL images and Numeric arrays

SPIDER formats are handled by a module called SpiderImagePlugin.py in the lib/python/site-packages/PIL directory.