数字图像处理与Python实现-图像降噪-邻域平均

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/wujuxKkoolerter/article/details/102733108

图像降噪-平滑滤波-邻域平均

邻域平均法是一种局部空间域的简单处理算法。这种方法的基本思想是,在图像空间,假定有一幅图像大小为 N × N N \times N 个像素的图像 f ( x , y ) f(x,y) ,用邻域内几个像素的平均值去代替图像中的每一个像素点值的操作(即将一个像素及其邻域内的所有像素的平均灰度值赋给平滑图像中对应的像素)。经过平滑处理后得到一幅图像 g ( x , y ) g(x,y) 。其数学表达式如下:

g ( x , y ) = 1 M ( m , n ) s f ( m , n ) (2-1) g(x,y) = \frac{1}{M}\sum_{(m,n) \in s}f(m,n) \tag{2-1}

其中, x , y = 0 , 1 , 2 , . . . N 1 x,y=0,1,2,...N-1 ;s为点邻域中像素坐标的集合,其中不包括 ( x , y ) (x,y) 点;M为集合s内像素坐标点的总数。

Python实现的代码如下:


def convolve2d(img,fil,mode = 'same'):                #分别提取三个通道
    
    if mode == 'fill':
        h = fil.shape[0] // 2
        w = fil.shape[1] // 2
        img = np.pad(img, ((h, h), (w, w),(0, 0)), 'constant')
    conv_b = _convolve2d(img[:,:,0],fil)              #然后去进行卷积操作
    conv_g = _convolve2d(img[:,:,1],fil)
    conv_r = _convolve2d(img[:,:,2],fil)

    dstack = np.dstack([conv_b,conv_g,conv_r])      #将卷积后的三个通道合并
    return dstack                                   #返回卷积后的结果

def _convolve2d(img,fil):         
    
    fil_heigh = fil.shape[0]                        #获取卷积核(滤波)的高度
    fil_width = fil.shape[1]                        #获取卷积核(滤波)的宽度
    
    conv_heigh = img.shape[0] - fil.shape[0] + 1    #确定卷积结果的大小
    conv_width = img.shape[1] - fil.shape[1] + 1

    conv = np.zeros((conv_heigh,conv_width),dtype = 'uint8')
    
    for i in range(conv_heigh):
        for j in range(conv_width):                 #逐点相乘并求和得到每一个点
            conv[i][j] = wise_element_sum(img[i:i + fil_heigh,j:j + fil_width ],fil)
    return conv
    
def wise_element_sum(img,fil):
    res = (img * fil).sum() 
    if(res < 0):
        res = 0
    elif res > 255:
        res  = 255
    return res


src = imageio.imread('resources/images/f1.jpg')


kernel = np.array([[1.0,1.0,1.0],[1.0,2.0,1.0],[1.0,1.0,1.0]]) / 9.0



程序运行的结果如下:

在这里插入图片描述

左边图像为原图,右边为平滑后的图像

猜你喜欢

转载自blog.csdn.net/wujuxKkoolerter/article/details/102733108