实验3.1:高斯滤波
高斯滤波主要是求解模板,然而二维高斯滤波的计算过于复杂,鉴于二维高斯函数的可分离性,需要用一维的高斯滤波对计算进行优化,还有需要注意到边界的处理问题,这里直接把边界扩大一个center大小(2*center+1=size,size为模板大小,计算公式由题目给出)。在进行滤波的时候还需要注意到归一化以及变量类型的问题,不然会导致最后结果出错。
前图为原图,后图为高斯滤波后的图像。Sigma为2
Code
function []=test3_11(sigma,I)
tsize=floor((6*sigma-1)/2)*2+1;
tcenter=floor(tsize/2);
[m,n,~]=size(I);
newimg=zeros(m+2*tcenter,n+2*tcenter,3);
result1=zeros(m,n,3);
window=zeros(tsize,1);
newimg(tcenter+1:m+tcenter,tcenter+1:n+tcenter,:)=I(:,:,:);
sum=0;
for i=1:tsize
window(i,1)=1/(sigma*(2*pi)^(1/2))*exp(-(i-tcenter-1)^2/(2*sigma^2));
sum=sum+window(i,1);
end
window=window/sum;
for i=1:m
for j=1:n
R=0;
G=0;
B=0;
for q=1:tsize
R=R+window(q,1)*newimg(i+tcenter,j+q-1,1);
G=G+window(q,1)*newimg(i+tcenter,j+q-1,2);
B=B+window(q,1)*newimg(i+tcenter,j+q-1,3);
end
result1(i,j,1)=R;
result1(i,j,2)=G;
result1(i,j,3)=B;
end
end
img2=zeros(m+2*tcenter,n+2*tcenter,3);
result2=zeros(m,n,3);
img2(tcenter+1:m+tcenter,tcenter+1:n+tcenter,:)=result1(:,:,:);
for i=1:n
for j=1:m
R=0;
G=0;
B=0;
for q=1:tsize
R=R+window(q,1)*img2(j+q-1,i+tcenter,1);
G=G+window(q,1)*img2(j+q-1,i+tcenter,2);
B=B+window(q,1)*img2(j+q-1,i+tcenter,3);
end
result2(j,i,1)=R;
result2(j,i,2)=G;
result2(j,i,3)=B;
end
end
result2=uint8(result2);
figure;imshow(I)
figure;imshow(result2)
实验3.2:快速均值滤波
均值滤波可以算得上是最简单的滤波方法了,直接对模板内的值求和取均值即可,而这里要求利用积分图加速,也比较简单。类似与动态规划,却没有其复杂。需要注意的就是计算到最后,和可能比较大,需要uint32类型的比较合适。左图为原图,右图为均值滤波后的图像。滤波模板半径为3
Code
img=imread('22.png');
template=3;
I=uint32(img);
newImg=I;
[m,n,~]=size(I);
R=uint32(zeros(m,n));
G=uint32(zeros(m,n));
B=uint32(zeros(m,n));
for i=1:m
for j=1:n
if i==1&&j==1
R(i,j)=I(i,j,1);
G(i,j)=I(i,j,2);
B(i,j)=I(i,j,3);
elseif i==1
R(i,j)=I(i,j,1)+R(i,j-1);
G(i,j)=I(i,j,2)+G(i,j-1);
B(i,j)=I(i,j,3)+B(i,j-1);
elseif j==1
R(i,j)=I(i,j,1)+R(i-1,j);
G(i,j)=I(i,j,2)+G(i-1,j);
B(i,j)=I(i,j,3)+B(i-1,j);
else
R(i,j)=I(i,j,1)+R(i-1,j)+R(i,j-1)-R(i-1,j-1);
G(i,j)=I(i,j,2)+G(i-1,j)+G(i,j-1)-G(i-1,j-1);
B(i,j)=I(i,j,3)+B(i-1,j)+B(i,j-1)-B(i-1,j-1);
end
end
end
for i=template+2:m-template-1
for j=template+2:n-template-1
newImg(i,j,1)=(R(i+template,j+template)+R(i-template-1,j-template-1)-R(i-template-1,j+template)-R(i+template,j-template-1))/((template*2+1)^2);
newImg(i,j,2)=(G(i+template,j+template)+G(i-template-1,j-template-1)-G(i-template-1,j+template)-G(i+template,j-template-1))/((template*2+1)^2);
newImg(i,j,3)=(B(i+template,j+template)+B(i-template-1,j-template-1)-B(i-template-1,j+template)-B(i+template,j-template-1))/((template*2+1)^2);
end
end
newImg=uint8(newImg);
figure;imshow(img);
figure;imshow(newImg);