簡介
sobel算子是圖像邊緣檢測的最重要的算子之一,在機器學習,數字媒體、計算機視覺等領域起着重要作用。本文主要介紹sobel算子的計算過程。python實現過程和python中相關函數的介紹。方便讀者實際中使用。
原理
邊緣是指在圖像上像素灰度變化最顯著的地方,邊緣檢測算子則利用圖像邊緣灰度的突變來檢測邊緣。Sobel算子包含兩組3X3的濾波器,分別對水平和垂直方向上的邊緣敏感。
讓兩個方向模板分別沿着X軸、Y軸與圖像做卷積,方向是從上到下和從左到右。將模板的中心和圖像上的某個像素重合,並將該像素周圍的點與模板上的系數相乘,如(3)和(4)所示,其中G(x)和G(y)分別表示橫向及縱向邊緣檢測的圖像梯度值。
G(X) = (X3 + 2X6 + X9)-(X1 + 2X4 + X7)
G(Y) = (X1 +2X2 +X3) - (X7 + 2X8 + X9)
圖像上每個像素點的橫向及縱向梯度值通過如下公式結合,來計算該點梯度值G的大小:
G = √Gx2+Gy2
為了減少運算時間,提高運算效率,可以使用絕對值求和近似的方法代替開平方:
G = ¦Gx¦ + ¦Gy ¦
最后選取合適的閾值,將像素點的灰度值與閾值進行比較,若大於閾值,則改點為圖像的邊緣點。由於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)
————————————————
原文鏈接:https://blog.csdn.net/weixin_41500849/article/details/80611263