Edge Detection: Sobel operator

来源:互联网 发布:activiti java 代码 编辑:程序博客网 时间:2024/05/01 23:49

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 filteror 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 - 1kernelRowBase = pixelRow - 1sum = 0for row in range(kernelRowBase, kernelRowBase+3):for col in range(kernelColumnBase, kernelColumnBase+3):kColIndex = col - kernelColumnBasekRowIndex = row - kernelRowBaseapixel = anImage.getPixel(col, row)intensity = apixel.getRed() # gray scale imagesum = sum + intensity * kernel[kRowIndex][kColIndex]return sumimport mathdef 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


原创粉丝点击