PIL altrenatives?

Carl Banks imbosol-1049311994 at aerojockey.com
Wed Apr 2 22:46:28 CEST 2003


Max Khesin wrote:
> I am looking for a python func to do edge detection. A good function would
> be a version of im.point(func), where func would be passed the pixel's
> neighbourhood, so that different edges can be produced. As far as I can tell
> PIL does not support this directly. Of course, this could probably be done
> with PIL the long way, by getting individual pixels. But are there
> alternatives? Also, is there a good source for PIL code samples?


You can use Numeric, along with clever slicing, to do a whole edge
detect in one swoop.  I explained how to do something similar, a
cellular automaton, in another thread:

http://tinyurl.com/8ori

Basically, what you do is convert the image to a Numeric array
(this example assumes you have a grayscale image):

    width,height = image.size
    array = Numeric.fromstring(image.tostring(),Numeric.UnsignedInt8)
    array = Numeric.reshape(array,(height,width))

It sucks, but Numeric arrays are arraged in reverse order from Image
arrays, so you have to reverse width and height.  It would be helpful
for you to change the type of the array into Float:

    array = array.astype(Numeric.Float)

Then do the edge detect operation.  Maybe something like this
(my expample is very primitive, and probably wrong, of course):

    edge = Numeric.zeros((height-2,width-2),Numeric.Float)
    edge += array[1:-1,1:-1]
    edge -= 0.25*array[2:,1:-1]
    edge -= 0.25*array[1:-1,2:]
    edge -= 0.25*array[:-2,1:-1]
    edge -= 0.25*array[1:-1,:-2]

Then it back to an image:

    edge = edge.astype(Numeric.UnsignedInt8)
    edgeimage = Image.fromstring('L',(width-2,height-2),edge.tostring())

I hope you get the idea.


-- 
CARL BANKS





More information about the Python-list mailing list