Edge Detection: Sobel operator

12 篇文章 0 订阅
6 篇文章 0 订阅

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值