濾波算子簡介
ndimage
中提供了卷積算法,并且建立在卷積之上,提供了三種邊緣檢測的濾波方案:prewitt
, sobel
以及laplace
。
在convolve中列舉了一個(gè)用于邊緣檢測的濾波算子,統(tǒng)一維度后,其 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} ??1?1?1?000?111? ?, ??101??101??101? ?
此即prewitt
算子。
Sobel算子為Prewitt增添了中心值的權(quán)重,記為
[ ? 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} ??1?2?1?000?121? ?, ??101??202??101? ?
這兩種邊緣檢測算子,均適用于某一個(gè)方向,ndimage
還提供了lapace
算子,其本質(zhì)是二階微分算子,其
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}, ??1?1?1?1?18?1??1?1?1? ?,
具體實(shí)現(xiàn)
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
表示卷積過程中對(duì)邊緣效應(yīng)的彌補(bǔ)方案,設(shè)待濾波數(shù)組為a b c d
,則在不同的模式下,對(duì)邊緣進(jìn)行如下填充
左側(cè)填充 | 數(shù)據(jù) | 右側(cè)填充 | |
---|---|---|---|
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濾波以及l(fā)aplace濾波封裝在了一個(gè)字典中。其中origin
表示原始圖像,對(duì)應(yīng)的函數(shù)是一個(gè)lambda
表達(dá)式。
在繪圖時(shí),通過將cmap
映射到plt.cm.gray
,使得繪圖之后表現(xiàn)為灰度圖像。
效果如下文章來源:http://www.zghlxwxcb.cn/news/detail-437768.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-437768.html
到了這里,關(guān)于Python邊緣檢測之prewitt, sobel, laplace算子的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!