简介

 sobel算子是图像边缘检测的最重要的算子之一,在机器学习、数字媒体、计算机视觉等领域起着重要作用。由Irwin Sobel在1968年的一次博士课题讨论会上提出。本文主要介绍了Sobel算子的计算过程,python实现过程和python中相关函数的介绍。方便读者实际使用。

原理

 边缘是指在图像上像素灰度变化最显著的地 方,边缘检测算子则利用图像边缘灰度的突变来检 测边缘。Sobel算子包含两组3×3的滤波器,分别对水平及垂直方向上的边缘敏感。


Gx=⎡⎣⎢x1x4x7x2x5x8x3x6x9⎤⎦⎥=⎡⎣⎢−1−2−1000121⎤⎦⎥(1) (1) G x = [ x 1 x 2 x 3 x 4 x 5 x 6 x 7 x 8 x 9 ] = [ − 1 0 1 − 2 0 2 − 1 0 1 ]



Gy=⎡⎣⎢x1x4x7x2x5x8x3x6x9⎤⎦⎥=⎡⎣⎢10−120−210−1⎤⎦⎥(2) (2) G y = [ x 1 x 2 x 3 x 4 x 5 x 6 x 7 x 8 x 9 ] = [ 1 2 1 0 0 0 − 1 − 2 − 1 ]

x x 轴、yy轴与图像做卷积,方向是从上到下和从左到右。将模板的中 心和图像上的某个像素重合,并将该像素周围的点 与模板上对应的系数相乘,如式(3) ( 3 ) 和式(4) ( 4 ) 所示,其 中Gx G x 及Gy G y 分别代表经横向及纵向边缘检测的图像梯度值。


Gx=(x3+2x6+x9)−(x1+2x3+x5)(3) (3) G x = ( x 3 + 2 x 6 + x 9 ) − ( x 1 + 2 x 3 + x 5 )



Gy=(x7+2x8+x9)−(x1+2x2+x3)(4) (4) G y = ( x 7 + 2 x 8 + x 9 ) − ( x 1 + 2 x 2 + x 3 )

(5) ( 5 ) 结合,来计算该点梯度值G G 的大小:


G=G2x+G2y−−−−−−−√(5)(5)G=Gx2+Gy2


 为了减少运算时间,提高运算效率,可以使用绝 对值求和近似的方法代替开平方:


G=|Gx|+|Gy|(6) (6) G = | G x | + | G y |


  最后选取合适的阈值,将像素点的灰度值与阈 值进行比较,若大于阈值,则该点则为图像边缘点。 由于Sobel算 子对于象素的位置的影响做了加权,可以降低边缘 模糊程度,与Prewitt算子、Roberts算子相比效果更好。

python实现

 sobel算子在python中的实现有两种途径:opencv和skimage。全部代码如下:

from skimage import data,filters,img_as_ubyte
import matplotlib.pyplot as plt
import cv2

# 图像读取
img = data.camera()
plt.imshow(img,plt.cm.gray)

'''**********skimage*************'''
# sobel边缘检测
edges = filters.sobel(img)
# 浮点型转成uint8型
edges = img_as_ubyte(edges)
# 显示图像
plt.figure()
plt.imshow(edges,plt.cm.gray) 

# sobel 水平方向边缘检测
edgesh = filters.sobel_h(img)
edgesh = img_as_ubyte(edgesh)
plt.figure()
plt.imshow(edgesh,plt.cm.gray)

# sobel 竖直方向边缘检测
edgesv = filters.sobel_v(img)
edgesv = img_as_ubyte(edgesv)
plt.figure()
plt.imshow(edgesv,plt.cm.gray) 

'''**********opencv*************'''
# sobel边缘检测
edges = cv2.Sobel(img,cv2.CV_16S,1,1) 
# 浮点型转成uint8型
edges = cv2.convertScaleAbs(edges) 
plt.figure()
plt.imshow(edges,plt.cm.gray) 

# sobel 水平方向边缘检测
edges = cv2.Sobel(img,cv2.CV_16S,1,0) 
edgesh = cv2.convertScaleAbs(edgesh) 
plt.figure()
plt.imshow(edgesh,plt.cm.gray) 

# sobel 竖直方向边缘检测
edges = cv2.Sobel(img,cv2.CV_16S,0,1) 
edgesv = cv2.convertScaleAbs(edgesv) 
plt.figure()
plt.imshow(edgesv,plt.cm.gray)
效果



python对区域边缘光滑处理 python边缘计算_python实现


原图





python对区域边缘光滑处理 python边缘计算_灰度_02


基于skimage的全方向sobel检测





python对区域边缘光滑处理 python边缘计算_python对区域边缘光滑处理_03


基于skimage的竖直方向sobel检测





python对区域边缘光滑处理 python边缘计算_灰度_04


基于skimage的水平向sobel检测





python对区域边缘光滑处理 python边缘计算_python对区域边缘光滑处理_05


基于opencv的全方向sobel检测





python对区域边缘光滑处理 python边缘计算_灰度_06


基于opencv的竖直方向sobel检测





python对区域边缘光滑处理 python边缘计算_python实现_07


基于opencv的水平向sobel检测