python實現Sobel邊緣提取

參考文獻:

https://zh.wikipedia.org/wiki/索貝爾算子

代碼:

# reference : https://zh.wikipedia.org/wiki/索貝爾算子
from skimage import filters,io
import numpy as np
import matplotlib.pyplot as plt
gx = np.array([[-1,0,1],[-2,0,2],[-1,0,1]])
gy = np.array([[1,2,1],[0,0,0],[-1,-2,-1]])
#
def sobel(img):
    height = img.shape[0]
    width = img.shape[1]
    tmp_img = img.copy()
    for i in range(1,height-1):
        for j in range(1, width-1):
            tmpx = np.sum(np.sum(gx * img[i-1:i+2,j-1:j+2]))
            tmpy = np.sum(np.sum(gy * img[i-1:i+2,j-1:j+2]))
            tmp_img[i,j] = np.sqrt(tmpx**2 + tmpy **2)
    return tmp_img

img = io.imread("/Applications/Python/SuperpixelMethod/SLIC-master/6.jpg",as_gray=True)
sobel_img = filters.sobel(img)
sobel_img_my = sobel(img.copy())

print("ok")
plt.subplot(131)
plt.imshow(img,cmap="gray")
plt.title("Input Image")

plt.subplot(132)
plt.imshow(sobel_img)
plt.title("Using Sobel Lib from Skimage")

plt.subplot(133)
plt.imshow(sobel_img_my)
plt.title("Using Sobel Lib from Mine")
plt.show()

運行效果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章