Recent posts / Archive

Categories

Sobel Edge Detection

Originally posted by on 06:00 Wed 9 March 2005, last modified 20:04 Tue 5 June 2007.

File under: 3rd year project image processing programming python

Sobel edge detection is a popular technique as it can deliver good results, without excessive computational requirements. The technique utilises the theory of optimal smoothing (Gaussian), and optimal differencing.

The Gaussian smoothing can be obtained using Pascal's triangle, and the differencing can be given by Pascal's triangle for subtraction. A Python implementation to return the value of Pascal's triangle for a given window size (which means the depth of the triangle), and position is shown below:

def pascal(k,size):
    if 0 <= k <= size:
        return (factorial(size) / (factorial(size-k) * factorial(k)))
    else:
        return 0

This requires a factorial function, which is implemented very elegantly in Python below. Note that the factorial of 0, 0! = 1, this is due to the empty product. See Wikipedia for more info.

def factorial(n):
    if n == 0: return 1
    else: return reduce(lambda x,y:x*y, range(1,n+1),1)

This leads us to the smooth and difference functions....

def smooth(size, point):
    return (factorial(size - 1) / (factorial(size - 1 - point) * factorial(point)))
 
def diff(size, point):
    return pascal(point, size-2) - pascal(point-1, size-2)

A general Sobel template function, can then create either the X or the Y templates.

from numpy import zeros
def sobel(size, type):
    template = zeros((size,size))
    if type is "X":
        for y,x in [(x,y) for x in range(size) for y in range(size)]:
            template[y][x] = smooth(size,y) * diff(size,x)
    elif type is "Y":
        for x,y in [(x,y) for x in range(size) for y in range(size)]:
            template[y][x] = smooth(size,x) * diff(size,y)
    return template

And the resulting templates look like this for size 5:

template_X :=
[[ 1 2 0 -2 -1]
[ 4 8 0 -8 -4]
[ 6 12 0 -12 -6]
[ 4 8 0 -8 -4]
[ 1 2 0 -2 -1]]

template_Y :=
[[ 1 4 6 4 1]
[ 2 8 12 8 2]
[ 0 0 0 0 0]
[ -2 -8 -12 -8 -2]
[ -1 -4 -6 -4 -1]]

comment

Comment on article