How to make a Gaussian filter in Matlab

浪尽此生 提交于 2019-11-27 14:51:52

here's an alternative:

Create the 2D-Gaussian:

  function f=gaussian2d(N,sigma)
  % N is grid size, sigma speaks for itself
 [x y]=meshgrid(round(-N/2):round(N/2), round(-N/2):round(N/2));
 f=exp(-x.^2/(2*sigma^2)-y.^2/(2*sigma^2));
 f=f./sum(f(:));

Filtered image, given your image is called Im:

 filtered_signal=conv2(Im,gaussian2d(N,sig),'same');

Here's some plots:

imagesc(gaussian2d(7,2.5))

 Im=rand(100);subplot(1,2,1);imagesc(Im)
 subplot(1,2,2);imagesc(conv2(Im,gaussian2d(7,2.5),'same'));

This example code is slow because of the for-loops. In matlab you can better use conv2, as suggested by user:bla, or just use filter2.

I = imread('peppers.png'); %load example data
I = I(:,:,1);
N=5; %must be odd
sigma=1;
figure(1);imagesc(I);colormap gray
x=1:N;
X=exp(-(x-((N+1)/2)).^2/(2*sigma^2));
h=X'*X;
h=h./sum(h(:));
%I=filter2(h,I); %this is faster
[is,js]=size(I);
Ib = NaN(is+N-1,js+N-1); %add borders
b=(N-1)/2 +1;
Ib(b:b+is-1,b:b+js-1)=I;
I=zeros(size(I));
for i = 1:is
    for j = 1:js
        I(i,j)=sum(sum(Ib(i:i+N-1,j:j+N-1).*h,'omitnan'));
    end
end
figure(2);imagesc(I);colormap gray
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!