Excerpts from the Book: Python Programming in Context
http://en.wikipedia.org/wiki/Sobel_operator
In order to find an edge, it is necessary to evaluate each pixel in relation to those that appear around it. Since we are looking for places where intensity on one side of the pixel is greatly different from the intensity on the other ...
As a means of looking for these intensity differences, we use the idea of a kernel, also known as a filter or a mask. These kernels will be used to weight the intensities of the surrounding pixels ... Sobel operators, named after Irwin Sobel who developed them for use in edge detection. ...
The kernels will be used during convolution -- a process in which pixels in the original image will be mathematically combined with each mask. The result will then be used to decide whether that pixel represents an edge.
def convolve(anImage, pixelRow, pixelCol, kernel):
kernelColumnBase = pixelCol - 1
kernelRowBase = pixelRow - 1
sum = 0
for row in range(kernelRowBase, kernelRowBase+3):
for col in range(kernelColumnBase, kernelColumnBase+3):
kColIndex = col - kernelColumnBase
kRowIndex = row - kernelRowBase
apixel = anImage.getPixel(col, row)
intensity = apixel.getRed() # gray scale image
sum = sum + intensity * kernel[kRowIndex][kColIndex]
return sum
import math
def edgeDetect(theImage):
grayImage = pixelMapper(theImage, grayPixel)
newim = EmptyImage(grayImage.getWidth, grayImage.getHeight())
black = Pixel(0, 0, 0)
white = Pixel(255, 255, 255)
xMask = [[-1, -2, -1], [0, 0, 0], [1, 2, 1]]
yMask = [[1, 0, -1], [2, 0, -2], [1, 0, -1]]
for row in range(1, grayImage.getHeight()-1):
for col in range(1, grayImage.getWidth()-1):
gx = convolve(grayImage, row, col, xMask)
gy = convolve(grayImage, row, col, yMask)
g = math.sqrt(gx**2 + gy**2)
if g > 175:
newim.setPixel(col, row, black)
else:
newim.setPixel(col, row, white)
return newim