欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

均值滤波与中值滤波(python实现)

程序员文章站 2022-05-27 16:31:32
...

使用Python实现窗口滑动功能,并对椒盐噪声进行去噪,比较两者去噪效果。

均值滤波:

均值滤波与中值滤波(python实现)

中值滤波:中值滤波的实现原理是把数字图像中一点的值用该点的一个区域的各个点的值的中值代替。

import cv2
import numpy as np
from itertools import chain
def padding_0(img):
    a = np.insert(img, 0, 0, 0)
    b = np.insert(a, 0, 0, 0)
    c = np.insert(b, 0, 0, 1)
    d = np.insert(c, 0, 0, 1)
    h_zeros = np.zeros((d.shape[0], 1))
    e = np.hstack((d, h_zeros))
    f = np.hstack((e, h_zeros))
    w_zeros = np.zeros((1, f.shape[1]))
    g = np.vstack((f, w_zeros))
    img = np.vstack((g, w_zeros))

    # no_padding(img)
    return img

def middle_flite_pcopy(img):
    img = padding_0(img)
    for i in range(2, img.shape[0] - 2):
        for j in range(2, img.shape[1] - 2):
            mat = np.array(
                [[img[i - 2, j - 2], img[i - 2, j - 1], img[i - 2, j], img[i - 2, j + 1], img[i - 2, j + 1]],
                 [img[i - 1, j - 2], img[i - 1, j - 1], img[i - 1, j], img[i - 1, j + 1], img[i - 1, j + 1]],
                 [img[i, j - 2], img[i, j - 1], img[i, j], img[i, j + 1], img[i, j + 1]],
                 [img[i + 1, j - 2], img[i + 1, j - 1], img[i + 1, j], img[i + 1, j + 1], img[i + 1, j + 1]],
                 [img[i + 2, j - 2], img[i + 2, j - 1], img[i + 2, j], img[i + 2, j + 1], img[i + 2, j + 1]]])
            c = list(chain(*mat))
            sort_list = sorted(c)
            img[i, j] = sort_list[12]
    return img

def mean_fliter(img):
    img=padding_0(img)
    for i in range(2, img.shape[0] - 2):
        for j in range(2, img.shape[1] - 2):
            mat = np.array(
                [[img[i - 2, j - 2], img[i - 2, j - 1], img[i - 2, j], img[i - 2, j + 1], img[i - 2, j + 1]],
                 [img[i - 1, j - 2], img[i - 1, j - 1], img[i - 1, j], img[i - 1, j + 1], img[i - 1, j + 1]],
                 [img[i, j - 2], img[i, j - 1], img[i, j], img[i, j + 1], img[i, j + 1]],
                 [img[i + 1, j - 2], img[i + 1, j - 1], img[i + 1, j], img[i + 1, j + 1], img[i + 1, j + 1]],
                 [img[i + 2, j - 2], img[i + 2, j - 1], img[i + 2, j], img[i + 2, j + 1], img[i + 2, j + 1]]])
            mean = np.sum(mat) / 25
            img[i, j] = mean
    return img

img = cv2.imread("./noise11.jpg", 0)
img1 = cv2.imread("./noise11.jpg", 0)
img2 = mean_fliter(img/255)
middle_flite_pcopy_img = middle_flite_pcopy(img/255)
cv2.imshow("mean", img2)
cv2.imshow("middle", middle_flite_pcopy_img)
cv2.imshow("origenal", img1)
cv2.waitKey(0)

原图:                                                                                                            

 均值滤波与中值滤波(python实现) 

均值:

  均值滤波与中值滤波(python实现) 

中值:

均值滤波与中值滤波(python实现)

 

均值滤波本身存在着固有的缺陷,即它不能很好地保护图像细节,在图像去噪的同时也破坏了图像的细节部分,从而使图像变得模糊,不能很好地去除噪声点。特别是椒盐噪声
中值滤波采用非线性的方法,它在平滑脉冲噪声方面非常有效,同时它可以保护图像尖锐的边缘,选择适当的点来替代污染点的值,所以处理效果好,对椒盐噪声表现较好