小言_互联网的博客

关于数字图像处理中的几种滤波算法

296人阅读  评论(0)

关于数字图像处理中的几种滤波算法

# -*- coding: utf-8 -*-
"""
Created on 2021/3/24 18:40

# @Author  : desires19
"""
import numpy as np
import matplotlib.pyplot as plt
import sys
from PIL import Image


def loading_image(path):
    image = Image.open(path)
    image = np.array(image)
    r = image[:, :, 0]
    g = image[:, :, 1]
    b = image[:, :, 2]
    # print("loading image finish!")
    return r, g, b


'''图片填充'''


def padding(c):
    size = c.shape
    re_size = (size[0] + 2, size[1] + 2)
    row = 0  # 行
    col = 0  # 列
    l = [[0 for i in range(re_size[1])] for i in range(re_size[0])]

    while col < re_size[0]:  # 列 801
        while row < re_size[1]:  # 行 642
            if col == 0 or row == 0 or col == (re_size[0] - 1) or row == (re_size[1] - 1):
                l[col][row] = 0
            else:
                l[col][row] = c[col - 1][row - 1]
            row += 1
        col += 1
        row = 0
    re = np.asarray(l)
    re = re.reshape(re_size)
    # print("padding finish!")
    return re


def Fuzzy(c, filter):
    f_size = filter.shape
    c_size = c.shape
    # 定义卷积上下左右边界
    left = 0
    right = f_size[0] - 1
    top = 0
    bottom = f_size[1] - 1
    l = []
    r = 0
    f_row = 0  # 滤波器的行
    f_col = 0  # 滤波器的列
    while bottom < c_size[0]:
        while right < int(c_size[1]):
            '''大循环'''
            while f_col < f_size[0]:
                while f_row < f_size[1]:
                    '''小循环'''
                    r = r + filter[f_col][f_row] * c[top + f_col][left + f_row]
                    if r < 0:
                        r = 0
                    if r > 255:
                        r = 255
                    # print(r)
                    f_row += 1
                f_col += 1
                f_row = 0
            l.append(int(r + 0.5))
            r = 0
            right += 1
            left += 1
            f_row = 0  # 重新归零进行下一次卷积运算
            f_col = 0
        bottom += 1
        top += 1
        right = f_size[0] - 1
        left = 0
    re = np.asarray(l)
    re = re.reshape(c_size[0] - 2, c_size[1] - 2)
    return re


def Mid(c, n):
    c_size = c.shape
    # 定义卷积上下左右边界
    left = 0
    right = n - 1
    top = 0
    bottom = n - 1
    l = []
    r = []
    f_row = 0  # 滤波器的行
    f_col = 0  # 滤波器的列
    while bottom < c_size[0]:
        while right < c_size[1]:
            '''大循环'''
            while f_col < n:
                while f_row < n:
                    '''小循环'''
                    r.append(c[top + f_col][left + f_row])
                    # print(r)
                    f_row += 1
                f_col += 1
                f_row = 0
            r.sort()
            l.append(r[int((pow(n, 2) / 2))])
            r = []
            right += 1
            left += 1
            f_row = 0  # 重新归零进行下一次卷积运算
            f_col = 0
        bottom += 1
        top += 1
        right = n - 1
        left = 0
    re = np.asarray(l)
    re = re.reshape(c_size[0] - 2, c_size[1] - 2)
    return re


'''均衡化'''


def Equalization(p):
    count = 0
    x = []
    y = []
    while count < 256:
        x.append(count)
        y.append(0)
        count += 1
    ls = [x, y]
    # print("init finish!")
    y_1 = ls[1]
    size = p.shape
    row = 0
    col = 0
    count = 0
    re = []
    while col < size[0]:
        while row < size[1]:
            y_1[p[col][row]] += 1
            row += 1
        col += 1
        row = 0
        x = np.array(ls[0])
        y_0 = np.array(ls[1])
        y = y_0 / (size[0] * size[1])  # 归一化处理

    '''计算累计直方图'''
    num = 0
    dy = []  # 累计直方数组
    for n in y:
        num = num + n
        dy.append(num)
    '''取整处理'''
    sk = []  # 转化后
    for n in dy:
        num_1 = int(255 * n + 0.5)  # 四舍五入
        sk.append(num_1)
    '''处理映射关系'''
    col = 0  # 归零处理,重新循环,覆盖图像
    row = 0
    while col < size[0]:  # 列
        while row < size[1]:  # 行
            num_2 = p[col][row]
            re.append(sk[num_2])  # 进行映射
            row += 1
        col += 1
        row = 0
    im_re = np.array(re)
    im_re = im_re.reshape(size)
    return im_re


def image_show(r, g, b, image_name):
    new_image = np.stack((r, g, b), axis=2)
    # print(new_image.shape)
    plt.rcParams['savefig.dip'] = 400  # 图片像素
    plt.rcParams['figure.dip'] = 300  # 分辨率
    plt.imshow(new_image)  # 显示图片
    plt.axis('off')  # 不显示坐标轴
    plt.savefig(image_name, bbox_inches='tight')


def switch(state):
    if state == 1:
        '''高斯滤波器'''
        Gauss = np.asarray([[1, 2, 1], [2, 4, 2], [1, 2, 1]]) / 16

        g_r = Fuzzy(p_r, Gauss)
        g_g = Fuzzy(p_g, Gauss)
        g_b = Fuzzy(p_g, Gauss)
        image_show(g_r, g_g, g_b, 'E:\Documents\python_work\dpi\output\\gauss_1.jpg')
    elif state == 2:
        '''均值滤波器'''
        Average = np.asarray([[1, 1, 1], [1, 1, 1], [1, 1, 1]]) / 9
        a_r = Fuzzy(p_r, Average)
        a_g = Fuzzy(p_g, Average)
        a_b = Fuzzy(p_g, Average)
        image_show(a_r, a_g, a_b, 'E:\Documents\python_work\dpi\output\\average_2.jpg')

    elif state == 3:
        '''中值滤波器'''
        m_r = Mid(p_r, 3)
        m_g = Mid(p_g, 3)
        m_b = Mid(p_b, 3)
        image_show(m_r, m_g, m_b, 'E:\Documents\python_work\dpi\output\\mid_3.jpg')

    elif state == 4:
        '''锐化滤波器'''
        H_1 = np.asarray([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]])
        s_r = Fuzzy(p_r, H_1)
        s_g = Fuzzy(p_g, H_1)
        s_b = Fuzzy(p_b, H_1)
        image_show(s_r, s_g, s_b, 'E:\Documents\python_work\dpi\output\\strong_4.jpg')
    elif state == 0:
        '''均衡化处理'''
        e_r = Equalization(p_r)
        e_g = Equalization(p_g)
        e_b = Equalization(p_b)
        image_show(e_r, e_g, e_b, 'E:\Documents\python_work\dpi\output\\transform_0.jpg')

    elif state == 5:
        sys.exit()
def init():
    print("0为均衡化处理")
    print("1为高斯滤波")
    print("2为均值滤波")
    print("3为中值滤波")
    print("4为锐化滤波")
    print("5为退出程序")
    key = input("请输入您想要进行的操作 ")
    return key


if __name__ == '__main__':
    im_path = './example.jpg'

    r, g, b = loading_image(im_path)
    p_r = padding(r)
    p_g = padding(g)
    p_b = padding(b)
    '''
        0为均衡化处理
        1为高斯滤波
        2为均值滤波
        3为中值滤波
        4为锐化滤波
        
    '''
    while(1):
        k = eval(init())
        switch(k)

贴两张图片展示一下效果

原图


均衡化处理后的图像,整体像素分布更加平均,对人眼比较友好


高斯滤波后的图像,采用的核更加强调中心的像素点


均值滤波的图像,像素点和其八邻域内的像素点对中心像素点有相同的权重作用

中值滤波算子,取像素点和其八邻域内像素的中位数


锐化算子,常用于边缘检测


转载:https://blog.csdn.net/weixin_46306088/article/details/115480132
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场