[Image-SIG] Where do these methods come from?

Nils de Reus nils.de.reus at ivm.vu.nl
Thu Jan 21 13:16:09 CET 2010


> Hi there,
> 
> I am confused of the PIL code, I tried to write a custom non-linear filter
> that's the reason why I took a look.
> 
> Can someone give me a hint how this works:
> 
> ImageFilter.py, class RankFilter:
> 
> In the method "filter" which takes an image (which is obviously an Image()?) a
> method "image.rankfilter" is called. I cannot call this method on an image I
> e.g. loaded from a file and can't find it elsewhere in the code.

rankfilter is a method of class ImagingCore, which is implemented in _imaging.so. You cannot call this method directly on your image class, but you can get to the ImagingCore of any PIL Image class through the im property, like this:

>>> im = Image.open("/tmp/pic.jpg")
>>> im
<JpegImagePlugin.JpegImageFile instance at 0x1be1b48>
>>> im.im
<ImagingCore object at 0x7fa5f63e30d8>
>>> im.im.rankfilter
<built-in method rankfilter of ImagingCore object at 0x7fa5f63e30d8>



> The other thing I originally planned was to write an own filter. I started
> with:
> 
> ####
> 
> import Image
> from ImageFilter import *
> 
> class BinomialFilter(Filter):
> 
>     name = "BinomialFilter"
> 
>    def __init__(self, scale=1):
>         self.scale = 16
>         self.offset = 1
>         self.filtermatrix = [[1, 2, 1],[2, 4, 2],[1, 2, 1]]
> 
>     def filter(self, image):
>         # convert to grayscale
>         im = image.convert("L")
>         return im
> 
> im = Image.open("/tmp/pic.jpg")
> im.filter(BinomialFilter()).show()
> 
> ###
> 
> which I thought should return me a grayscale image. But it
> returns a coloured image. What's wrong here?

When you filter a multiband image (your color jpg would have R, G and B bands), each individual band is sent through the filter function as a single-band image, and afterwards the filtered bands are merged back together as an image of the same mode as the original.

So what is happening here is that you convert the R, G and B bands to L mode each on their own, and then merge the three L-mode images together into a three-band RGB mode image.. which is indeed a color image pretty indistinguishable from what you started with.


Kind regards,
    Nils



More information about the Image-SIG mailing list