#MATLAB#课程实践#图像处理

高斯滤波是图像处理中常用的一种方法,本文章采用扩充边缘的方法进行高斯滤波,分别生成原图,噪声图,二维高斯滤波的结果,一维高斯滤波的结果(两步),有助于学生理解更深刻的理解到高斯滤波二维模版与分解为一维模版效果相同(因为四舍五入的原因略有差别,但在误差允许范围内)。

可以换原图像(要保证图像与.m文件在一个文件夹里)

​
clear all;
close all;
% 扩展原图像的高斯滤波
originimg=imread('smile.jpg');%导入原图像,可更改
originimg=rgb2gray(originimg);
[ori_row,ori_col]=size(originimg);

sigma = 2;      %sigma赋值
N = 6;            %大小是(2N+1)×(2N+1)
N_row = 2*N+1;
 
OriImage_noise = imnoise(originimg,'gaussian'); %加噪,为使结果更清晰
 
%求高斯模板H 
H = [];                                       
for i=1:N_row
    for j=1:N_row
        fenzi=double((i-N-1)^2+(j-N-1)^2);
        H(i,j)=exp(-fenzi/(2*sigma*sigma))/(2*pi*sigma);
    end
end

H=H/sum(H(:));              %归一化
 
H_Z = round(H* (1 / H(1,1)));%整数化

desimg=zeros(ori_row,ori_col);            %定义滤波后图像
desimg1 = zeros(ori_row,ori_col);
desimg2 = zeros(ori_row,ori_col);

midimg=zeros(ori_row+2*N,ori_col+2*N);    %中间图像
for i=1:ori_row                           %原图像赋值给中间图像,四周边缘设置为0
    for j=1:ori_col
        midimg(i+N,j+N)=OriImage_noise(i,j);
    end
end

%直接高斯滤波
temp=[];
for ai=N+1:ori_row+N
    for aj=N+1:ori_col+N
        temp_row=ai-N;
        temp_col=aj-N;
        temp=0;
        for bi=1:N_row
            for bj=1:N_row
                temp= temp+(midimg(temp_row+bi-1,temp_col+bj-1)*H(bi,bj));
            end
        end
        desimg(temp_row,temp_col)=temp;
    end
end
desimg=uint8(desimg);

 % 对图像进行行方向卷积操作
 vertical_vector = H_Z(1, :);
 vertical_vector=vertical_vector/sum(vertical_vector(:));
 
 temp1=[];
 for ai=N+1:ori_row+N
    for aj=N+1:ori_col+N
        temp_row=ai-N;
        temp_col=aj-N;
        temp1=0;
        for bi=1:N_row
            
                temp1= temp1+(midimg(temp_row+bi-1,temp_col)*vertical_vector(bi));
            
        end
        desimg1(temp_row,temp_col)=temp1;
    end
end
    desimg1=uint8(desimg1);

 % 对图像进行列方向卷积操作
 horizontal_vector = H_Z(:, 1);
 horizontal_vector=horizontal_vector/sum(horizontal_vector(:));

desimg1_1=zeros(ori_row+2*N,ori_col+2*N);    %中间图像
for i=1:ori_row                           %desimg1图像赋值给中间图像,四周边缘设置为0,得到desimg1_1
    for j=1:ori_col
        desimg1_1(i+N,j+N)=desimg1(i,j);
    end
end

temp2=[];
for ai=N+1:ori_row+N
    for aj=N+1:ori_col+N
        temp_row=ai-N;
        temp_col=aj-N;
        temp2=0;
        for bj=1:N_row
             
                temp2= temp2+(desimg1_1(temp_row,temp_col+bj-1)*horizontal_vector(bj));
             
        end
        desimg2(temp_row,temp_col)=temp2;
    end
end
    desimg2=uint8(desimg2);
 
subplot(3,2,1);imshow(originimg);title('原图');
subplot(3,2,2);imshow(OriImage_noise);title('噪声图');
subplot(3,2,3);imshow(desimg);title('高斯滤波');
subplot(3,2,5);imshow(desimg1);title('行高斯滤波');
subplot(3,2,6);imshow(desimg2);title('行*列高斯滤波');

​

 如果有任何可以优化的地方,欢迎评论。

参考了:MATLAB实现图像滤波--高斯滤波——猫宁大人

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐