converting between PIL and NumPY

Travis Oliphant Oliphant.Travis at mayo.edu
Tue Oct 5 13:03:54 EDT 1999


> Could someone send me some quick info on converting between a PIL object
> and a NumPy array?  (I seem to recall this being discussed in August,
> but I can't find it in deja.com.  Are there any better places to look? I
> really hate deja.com.)

For now you have to use the tostring() method of one object and use the
fromstring command of the other toolkit.  If both objects implemented
the (new in Python 1.5.2) buffer interface you could do this without
having two copies of the same basic data.

I have only really tried to do it for PIL images of type 'L' (8-bit
char).

To get PIL object: (suppose num_image is a 2-D numpy array)
This will give an 8-bit image so you lose informtion.

import Image
import gist       # contains the bytscl command which returns 8-bit data
	          # from whatever NumPy array you give it
imsize = list(num_image.shape)
imsize.reverse()  # the shape is reversed from NumPy standard
imstring = gist.bytscl(num_image,top=255).tostring()
im=Image.fromstring('L',imsize,imstring)

To get a NumPy array (of type UnsignedInt8) from a PIL image (of type 'L')

import Numeric
num_image = Numeric.fromstring(im.tostring(),Numeric.product(im.size),'b')
num_image.shape = Numeric.array(im.size)[::-1]

To convert to and from other PIL types is similar.

> 
> I want to do some image filtering with my own routines.  Has anyone
> written a wrapper routine that slides a moving window over an image and
> provides these values to a python list (or numpy array) for a user
> defined routine to process?  If not, I may roll my own.

Nothing quite so general.  I do have some general purpose convolution
routines in signaltools if your filtering is linear and shift invariant
(i.e. can be written as a convolution). You can find signaltools at
http://oliphant.netpedia.net

If you come up with a general way to do this kind of "moving window
arbitrary filtering" in a fast way (i.e. no Python for loop), and you
would let me make it a part of signaltools, I'd love to know about it.

Best,

Travis









More information about the Python-list mailing list