1D Gaussian filter horizontally and vertically
A convolution with 2D Gaussian can be performed with two 1D Gaussians as:
G(x,y)*I=G(x)*(G(y)*I);
You can do this in MATLAB as follows:
img=im2double(imread('cameraman.tif'));
yourFilterSize=[3 5] %3 rows, 5 columns, can be anything
%two 1D Gaussians
g_x=fspecial('gaussian',[1 yourFilterSize(2)]);
g_y=fspecial('gaussian',[yourFilterSize(1) 1]);
%applying 1D gaussian in X-direction to the original image
img_X=imfilter(img,g_x);
%applying 1D gaussian in Y-direction to img_X
img_XY=imfilter(img_X,g_y); %DONE
%verifying that the result is correct
g_xy=fspecial('gaussian',yourFilterSize);
img_XY2D=imfilter(img,g_xy);
max(max(abs(img_XY-img_XY2D))) %this should be very small,
%of the order of machine precision
%for the result to be correct
Additional reading:
- This answer on Stackoverflow.com which shows you how to determine whether a given kernel is separable. For example, Gaussian is separable, while the disk kernel is not.
- Original article for above mentioned issue.
Why would you prefer two 1D convolutions instead of one 2D convolution (also given in the link 2 mentioned above):
Suppose you have an image of size MxN
and a filter of size PxQ
then for a 2D convolution, you need ~ M*P*N*Q
multiplications and additions. For two 1D filters (of size P
and Q
), you only need ~ MNP+MNQ = MN(P+Q)
operations. Therefore, you get a speedup of the order of PQ/(P+Q)
.
seereen
Student in UWO , ... need some help from lovely people in this website :D
Updated on June 04, 2022Comments
-
seereen almost 2 years
I am trying to generate Gaussian filter that can be applied on the images, but I want to apply it 1D twice: horizontally and vertically. In addition, I want to apply it to each planes separately.
That mean I want to design 1D Gaussian filter to apply it horizontally in Red, Green, Blue component, then I have the same 1D Gaussian filter to apply it vertically in Red, Green, Blue component.
And I think this operation should equal applying 2D Gaussian filter on the original color image.
I am new in Matlab and in image processing filter.
-
seereen over 9 yearsThanks Parag S. Chandakkar for your help ... I have question, why you select [ 3 3] ? .... how can determine the size here?
-
Autonomous over 9 yearsThat's just an example. Please check the updated answer. If you find the answer helpful, please accept it by clicking the check mark on the left hand side.