matlab高斯滤波器

1、使用matlab自带的函数

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear;

	img = imread('lena.tif');
	w = fspecial('gaussian',[5,5],1);
	%replicate:图像大小通过赋值外边界的值来扩展
	%symmetric 图像大小通过沿自身的边界进行镜像映射扩展
	I11 = imfilter(img,w,'replicate');
	figure(1);
	imshow(img);title('原图像');
	figure(2);
	imshow(I11);title('matlab高斯滤波后的图像');

结果:可以看到帽子和头发都非常显著的平滑了

matlab高斯滤波器_第1张图片matlab高斯滤波器_第2张图片

2、自己编写的高斯滤波函数

%own gaussian function 
I = imread('lena.tif');
I = double(I);%convert unit8 to double 
myimg = I;
[rows, cols] = size(I);
size = 5;
conv = zeros(size,size);%高斯核
segma = 1;
sum = 0;
center  = 3;
for i=1:size
	for j=1:size
		%%利用高斯函数计算模板的各个参数
		temp = exp ( -((i-center)*(i-center) + (j-center)*(j-center)) / 2*segma*segma );
		conv(i,j) = temp / (2*3.14*segma*segma);
		sum =sum +  conv(i,j);
	end
end
conv = conv ./ sum;
disp('kernel');
display(conv);
%use gaussian kernel to smooth image
for k=1:rows
	for m= 1:cols
	    sum =0;
		%%卷积:模板与图像对应部分相乘再累加
		for i=1:size
			for j=1:size
				if( ( (k-center+i) > 0 && (k-center+i) <= rows ) && ((m-center+j)>0 && (m-center+j)<=cols) )
					sum = sum + conv(i,j) * I(k-center+i, m-center+j);
				end
			end
		end
		%%替换掉原像素
		myimg(k,m) = sum;
	end
end
figure(3);
imshow(myimg,[]);
title('Gaussion Image');
			

matlab高斯滤波器_第3张图片

结论:使用自己编写的滤波,虽然也起到了平滑效果,但是图像亮度偏高些,还不知道原因,希望大神指点指点。

你可能感兴趣的:(图像处理)