Rcjp's Weblog

April 2, 2008

Gaussian PIL Image Filter

Filed under: python — rcjp @ 6:54 pm

I could not see a gaussian filter in the python imaging library, but its simple enough to write one…

import ImageFilter
from PIL import Image
from numpy import *

def gaussian_grid(size = 5):
    """
    Create a square grid of integers of gaussian shape
    e.g. gaussian_grid() returns
    array([[ 1,  4,  7,  4,  1],
           [ 4, 20, 33, 20,  4],
           [ 7, 33, 55, 33,  7],
           [ 4, 20, 33, 20,  4],
           [ 1,  4,  7,  4,  1]])
    """
    m = size/2
    n = m+1  # remember python is 'upto' n in the range below
    x, y = mgrid[-m:n,-m:n]
    # multiply by a factor to get 1 in the corner of the grid
    # ie for a 5x5 grid   fac*exp(-0.5*(2**2 + 2**2)) = 1
    fac = exp(m**2)
    g = fac*exp(-0.5*(x**2 + y**2))
    return g.round().astype(int)

class GAUSSIAN(ImageFilter.BuiltinFilter):
    name = "Gaussian"
    gg = gaussian_grid().flatten().tolist()
    filterargs = (5,5), sum(gg), 0, tuple(gg)


im = Image.open('/home/rcjp/tmp/test.png')
im1 = im.filter(GAUSSIAN)
im1.save('/home/rcjp/tmp/testfiltered.png')

Advertisements

2 Comments »

  1. Thanks. I am using a normal pdf to disperse a 2d spatial population at each time step in a grid map. This is close to what i need.

    Jon

    Comment by Jon Allen — August 7, 2009 @ 1:55 pm

  2. As of 1.1.5 there appears to be Gaussian Blur in the PIL, but I don’t think it’s documented. I wrote a quick post about it:

    http://aaronfay.ca/content/post/python-pil-and-gaussian-blur/

    Regards,

    Comment by Aaron Fay — May 28, 2011 @ 6:39 pm


RSS feed for comments on this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: