????????之前介紹的均值濾波、方框濾波、高斯濾波,都是線性濾波方式。由于線性濾波的結(jié)果是所有像素值的線性組合,因此含有噪聲的像素也會被考慮進去,噪聲不會被消除,而是以更柔和的方式存在。這時使用非線性濾波效果可能會更好。中值濾波與前面介紹的濾波方式不同,不再采用加權(quán)求均值的方式計算濾波結(jié)果。它用鄰域內(nèi)所有像素值的中間值來替代當前像素點的像素值。
5.1 原理介紹
????????中值濾波會取當前像素點及其周圍臨近像素點(一共有奇數(shù)個像素點)的像素值,將這些像素值排序,然后將位于中間位置的像素值作為當前像素點的像素值。 對如下矩陣:
????????將其鄰域設置為3×3大小,對其3×3鄰域內(nèi)像素點的像素值進行排序(升序降序均可),按升序排序后得到序列值為:[66,78,90,91,93,94,95,97,101]。在該序列中,處于中心位置(也叫中心點或中值點)的值是“93”,因此用該值替換原來的像素值78,作為當前點的新像素值。中值濾波效果如下:
?5.2 函數(shù)語法
????????在OpenCV中,實現(xiàn)中值濾波的函數(shù)是cv2.medianBlur(),其語法格式如下:
???????? dst=cv2.medianBlur(src,ksize)
????????式中:
????????● dst是返回值,表示進行中值濾波后得到的處理結(jié)果。
???????? ● src 是需要處理的圖像,即源圖像。它能夠有任意數(shù)量的通道,并能對各個通道獨立處理。圖像深度應該是CV_8U、CV_16U、CV_16S、CV_32F 或者 CV_64F中的一種。
????????● ksize 是濾波核的大小。濾波核大小是指在濾波處理過程中其鄰域圖像的高度和寬度。需要注意,核大小必須是比1大的奇數(shù),比如3、5、7等。?
5.3 程序?qū)嵗?/h2>
import cv2 as cv
def cv_show(name, img):
cv.imshow(name, img)
cv.waitKey(0)
cv.destroyAllWindows()
def add_peppersalt_noise(image, n=10000):
result = image.copy()
# 測量圖片的長和寬
w, h =image.shape[:2]
# 生成n個椒鹽噪聲
for i in range(n):
x = np.random.randint(1, w)
y= np.random.randint(1, h)
if np.random.randint(0, 2) == 0 :
result[x, y] = 0
else:
result[x,y] = 255
return result
img = cv.imread('D:\\dlam.jpg')
if img is None:
print('Failed to read the image')
img1 = add_peppersalt_noise(img)
cv_show('after', img1)
# 中值濾波,可對灰色圖像和彩色圖像使用
img2 = cv.medianBlur(img1, 3)
cv_show('after1', img2)
# ksize變大圖像變模糊
img3 = cv.medianBlur(img1, 9)
cv_show('after2', img3)
import cv2 as cv
def cv_show(name, img):
cv.imshow(name, img)
cv.waitKey(0)
cv.destroyAllWindows()
def add_peppersalt_noise(image, n=10000):
result = image.copy()
# 測量圖片的長和寬
w, h =image.shape[:2]
# 生成n個椒鹽噪聲
for i in range(n):
x = np.random.randint(1, w)
y= np.random.randint(1, h)
if np.random.randint(0, 2) == 0 :
result[x, y] = 0
else:
result[x,y] = 255
return result
img = cv.imread('D:\\dlam.jpg')
if img is None:
print('Failed to read the image')
img1 = add_peppersalt_noise(img)
cv_show('after', img1)
# 中值濾波,可對灰色圖像和彩色圖像使用
img2 = cv.medianBlur(img1, 3)
cv_show('after1', img2)
# ksize變大圖像變模糊
img3 = cv.medianBlur(img1, 9)
cv_show('after2', img3)
原圖如圖所示:
添加椒鹽噪聲:
3*3中值濾波效果:?
5*5中值濾波效果:?
文章來源:http://www.zghlxwxcb.cn/news/detail-461203.html
? ? ? ? ?可以看出中值濾波對噪聲的消除效果比線性濾波好,但是隨著濾波核的增大,圖像也會變模糊。文章來源地址http://www.zghlxwxcb.cn/news/detail-461203.html
到了這里,關于Opencv之圖像濾波:5.中值濾波(cv2.medianBlur)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!