How to make a Gaussian filter in Matlab

I tried to create a Gaussian filter in Matlab without using imfilter() and fspecial() . I tried this, but the result is not the same as mine with imfilter and fspecial.

Here are my codes.

 function Gaussian_filtered = Gauss(image_x, sigma) % for single axis % http://en.wikipedia.org/wiki/Gaussian_filter Gaussian_filtered = exp(-image_x^2/(2*sigma^2)) / (sigma*sqrt(2*pi)); end 

for two-dimensional Gaussian,

 function h = Gaussian2D(hsize, sigma) n1 = hsize; n2 = hsize; for i = 1 : n2 for j = 1 : n1 % size is 10; % -5<center<5 area is covered. c = [j-(n1+1)/2 i-(n2+1)/2]'; % A product of both axes is 2D Gaussian filtering h(i,j) = Gauss(c(1), sigma)*Gauss(c(2), sigma); end end end 

and the final -

 function Filtered = GaussianFilter(ImageData, hsize, sigma) %Get the result of Gaussian filter_ = Gaussian2D(hsize, sigma); %check image [r, c] = size(ImageData); Filtered = zeros(r, c); for i=1:r for j=1:c for k=1:hsize for m=1:hsize Filtered = Filtered + ImageData(i,j).*filter_(k,m); end end end end end 

But the processed image is almost the same as the input image. Interestingly, the last GaussianFiltered() function is problematic ...

Thanks.

+4
source share
2 answers

here's an alternative:

Create 2D Gaussian:

  function f=gaussian2d(N,sigma) % N is grid size, sigma speaks for itself [xy]=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 if your image is called Im :

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

Here are some graphs:

 imagesc(gaussian2d(7,2.5)) 

enter image description here

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

enter image description here

+20
source

This sample code is slow due to for-loops. In Matlab, you can better use conv2 as suggested by the 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 
0
source

Source: https://habr.com/ru/post/1443624/


All Articles