> 文章列表 > Python边缘检测之prewitt, sobel, laplace算子

Python边缘检测之prewitt, sobel, laplace算子

Python边缘检测之prewitt, sobel, laplace算子

文章目录

    • 滤波算子简介
    • 具体实现
    • 测试

滤波算子简介

ndimage中提供了卷积算法,并且建立在卷积之上,提供了三种边缘检测的滤波方案:prewitt, sobel以及laplace

在convolve中列举了一个用于边缘检测的滤波算子,统一维度后,其 x x x y y y向的梯度算子分别写为

[ − 1 0 1 − 1 0 1 − 1 0 1 ] , [ − 1 − 1 − 1 0 0 0 1 1 1 ] \\begin{bmatrix} -1&0&1\\\\-1&0&1\\\\-1&0&1\\\\ \\end{bmatrix}, \\begin{bmatrix} -1&-1&-1\\\\0&0&0\\\\1&1&1\\\\ \\end{bmatrix} 111000111 , 101101101

此即prewitt算子。

Sobel算子为Prewitt增添了中心值的权重,记为

[ − 1 0 1 − 2 0 2 − 1 0 1 ] , [ − 1 − 2 − 1 0 0 0 1 2 1 ] \\begin{bmatrix} -1&0&1\\\\-2&0&2\\\\-1&0&1\\\\ \\end{bmatrix}, \\begin{bmatrix} -1&-2&-1\\\\0&0&0\\\\1&2&1\\\\ \\end{bmatrix} 121000121 , 101202101

这两种边缘检测算子,均适用于某一个方向,ndimage还提供了lapace算子,其本质是二阶微分算子,其 3 × 3 3\\times3 3×3卷积模板可表示为

[ − 1 1 − 1 − 1 − 1 8 − 1 − 1 − 1 − 1 ] , \\begin{bmatrix} -1&1-1&-1\\\\-1&8&-1\\\\-1&-1&-1\\\\ \\end{bmatrix}, 1111181111 ,

具体实现

ndimage封装的这三种卷积滤波算法,定义如下

prewitt(input, axis=-1, output=None, mode='reflect', cval=0.0)
sobel(input, axis=-1, output=None, mode='reflect', cval=0.0)
laplace(input, output=None, mode='reflect', cval=0.0)

其中,mode表示卷积过程中对边缘效应的弥补方案,设待滤波数组为a b c d,则在不同的模式下,对边缘进行如下填充

左侧填充 数据 右侧填充
reflect d c b a a b c d d c b a
constant k k k k a b c d k k k k
nearest a a a a a b c d d d d d
mirror d c b a b c d c b a
wrap a b c d a b c d a b c d

测试

接下来测试一下

from scipy.ndimage import prewitt, sobel, laplace
from scipy.misc import ascent
import matplotlib.pyplot as plt
img = ascent()dct = {"origin" : lambda img:img,"prewitt" : prewitt,"sobel" : sobel,"laplace" : lambda img : abs(laplace(img))
}fig = plt.figure()
for i,key in enumerate(dct):ax = fig.add_subplot(2,2,i+1)ax.imshow(dct[key](img), cmap=plt.cm.gray)plt.ylabel(key)plt.show()

为了看上去更加简洁,代码中将原图、prewitt滤波、sobel滤波以及laplace滤波封装在了一个字典中。其中origin表示原始图像,对应的函数是一个lambda表达式。

在绘图时,通过将cmap映射到plt.cm.gray,使得绘图之后表现为灰度图像。

效果如下

在这里插入图片描述

华夏名砚网