clc; clear; close all;
Image=imread('lena.bmp');
sigma1=0.6; sigma2=10; r=3; % 高斯模板的参数
NoiseI= imnoise(Image,'gaussian'); % 加噪,添加高斯噪声
gausFilter1=fspecial('gaussian',[2*r+1 2*r+1],sigma1); % 高斯滤波器
gausFilter2=fspecial('gaussian',[2*r+1 2*r+1],sigma2);
result1=imfilter(NoiseI,gausFilter1,'conv'); % 使用卷积完成滤波
result2=imfilter(NoiseI,gausFilter2,'conv');
imshow(Image);title('原图');
figure;imshow(NoiseI);title('高斯噪声图像');
figure;imshow(result1);title('sigma1 =0.6高斯滤波');
figure;imshow(result2);title('sigma2 =10高斯滤波');
imwrite(uint8(NoiseI),'gr.bmp');
imwrite(uint8(result1),'gr1.bmp');
imwrite(uint8(result2),'gr2.bmp');
% 编写高斯滤波函数实现
[height,width]=size(NoiseI);
for x=-r:r
for y=-r:r
H(x+r+1,y+r+1)=1/(2*pi*sigma1^2).*exp((-x.^2-y.^2)/(2*sigma1^2));
end
end
H=H/sum(H(:)); %归一化高斯模板H
result3=zeros(height,width); %滤波后图像
midimg=zeros(height+2*r,width+2*r); %中间图像
midimg(r+1:height+r,r+1:width+r)=NoiseI;
for ai=r+1:height+r
for aj=r+1:width+r
temp_row=ai-r;
temp_col=aj-r;
temp=0;
for bi=1:2*r+1
for bj=1:2*r+1
temp= temp+(midimg(temp_row+bi-1,temp_col+bj-1)*H(bi,bj));
end
end
result3(temp_row,temp_col)=temp;
end
end
figure;imshow(uint8(result3));title('自己写的高斯滤波');
imwrite(uint8(result3),'gr3.bmp');
高斯噪声图像 :
Sigmal=0.6高斯滤波:
Sigmal=10高斯滤波:
自己写的高斯滤波:
Image=im2double(imread('lena.bmp'));
NoiseI= Image+0.05*randn(size(Image)); % 添加随机噪声
w=15; % 定义双边滤波窗口宽度
sigma_s=6; sigma_r=0.1; % 双边滤波的两个标准差参数
[X,Y] = meshgrid(-w:w,-w:w);
Gs = exp(-(X.^2+Y.^2)/(2*sigma_s^2)); % 计算邻域内的空间权值
[hm,wn] = size(NoiseI);
result=zeros(hm,wn);
for i=1:hm
for j=1:wn
temp=NoiseI(max(i-w,1):min(i+w,hm),max(j-w,1):min(j+w,wn));
Gr = exp(-(temp-NoiseI(i,j)).^2/(2*sigma_r^2)); % 计算灰度邻近权值
W = Gr.*Gs((max(i-w,1):min(i+w,hm))-i+w+1,(max(j-w,1):min(j+w,wn))-j+w+1); % W为空间权值Gs和灰度权值Gr的成绩
result(i,j)=sum(W(:).*temp(:))/sum(W(:));
end
end
subplot(1,3,1),imshow(Image),title('原始图像');
subplot(1,3,2),imshow(NoiseI),title('随机噪声图像');
subplot(1,3,3),imshow(result),title('双边滤波图像');
imwrite(NoiseI,'ng1.bmp');
imwrite(result,'ng2.bmp');