spatial filtering
TRANSCRIPT
BY
: RO
CH
EL
LE
LE
E
USING MATLAB IMAGEPROCESSING TOOL
SPATIAL FILTERING TECHNIQUESThe techniques used here include: Average Laplacian Gaussian Unsharp Prewitt Sobel Median
What is Spatial Filtering?
It is an image operation where each pixel value is changed by a function of the intensities of
pixels in a neighbourhood.
Why do we need Spatial Filters?It is necessary to highlight or suppress features
in an image based on spatial frequency such as suppressing noise or highlighting specific image characteristics. This is what spatial filters do.
h(x,y)
How does it work?
Spatial filtering involves selecting a specific mask or kernel of a particular size and correlating or convolving that mask on an input image to receive a new image; the output image which is less noise and more smooth.
The mask chosen is based upon the operation you wish to carry out on the image.
F(x,y) g(x,y) = f(x,y)**h(x,y)
Original image 2D Convolution Product
Output Image
.
CORRELATION CONVOLUTIONA process of moving the
filter mask over the image and computing the sum of products at each location
Correlation of a filter w(x,y) of size m*n with an image f(x,y)is:
A process of moving a previous 180 degrees rotated filter mask over the image and computing the sum of products at each location.
Convolution of a filter w(x,y) of size m*n with an image f(x,y) is:
w(x,y) f(x,y)= ∑∑w(s,t)f(x+s,y+t)
w(x,y) * F(x,y)= ∑∑ w(s,t)f(x-s,y-t)a
b .
LAPLACIAN FILTERINGDefined as the sum of the second derivatives
laplace operator and calculated as the sum of differenced over the nearest neighbours of the central pixel.
It uses highlights intensity discontinuities in the image and deemphasize regions with slow varying intensity levels.
It tends to produce images having greyish edge lines and other discontinuities and dark featureless background
One application operator is to restore fine detail to an image which has been smoothed to remove noise
The Laplacian L(x,y) of an image with pixel intensity values I(x,y) is given by: ∆^2f=d^2f/dx^2+d^2f/dy^2
The chosen kernels approximates the second derivative measurement on the image.
Original Image
Laplacian filter
Original image
Image resulted from convolving a laplacian mask
Image resulted after converting the image to type double and then
convolving with a laplacian mask
Image resulted from subtracting the laplacian
image from original Image
Code c=imread('ultra.jpg'); >> size(c)
ans =
1345 1741 3
>> c1=rgb2gray(c);%converting image to grayscale, working with a 2D image now >> size(c1)
ans =
1345 1741 >> % applying a laplacian filter >> w=fspecial('laplacian',0) % generating the laplacian mask
w =
0 1 0 1 -4 1 0 1 0
>> g1=imfilter(a,w,'replicate');% filtering image with the laplacian mask and the replicate is padding the image in the borders
>> figure,imshow(g1,[]) >> a22=im2double(a); >> g2=imfilter(a22,w,'replicate'); >> figure,imshow(g2,[]) >> g3=a22-g2; >> figure,imshow(g3,[]) >> figure,subplot(2,2,1),imshow(a,[]),subplot(2,2,2),imshow(g1,[]),subplot(2,2,3),imshow(g2,[]),subplot(2,2,4),imshow(g3,[])
Gaussian Smoothing
Gaussian filtering is done by convolving each point in the input array with a gaussian kernel and then summing them to produce the output.
It is the result of blurring an image by a gaussian function typically to reduce image noise and reduce detail. Formulae- G(x,y)=1/2пσ^2*е^-x^2+y^2/(2σ^2).
Where x is the distance from the original image in the horizontal axis.
Where y is the distance from the origin in the vertical axisWhere σ is the standard deviation of the gaussian
distributionThis formula produces a surface whose contours are
concentric circles with a gaussian distribution from the centre point. Values from this distribution are used to build a convolution matrix which is applied to the original image.
Choosing a sigma Value for Gaussian Smoothing
The sigma value can be thought of as an approximation of just how much you want the image to spread or blur in pixels.
It is also referred to as the population standard deviation.
Usually try to choose a sigma value which is 1/3 the filter mask you are using. Here the filter decays to nearly zero at edges and you avoid discontinuities in the filtered image.
The choice of sigma all depends on what you want to do.
Laplacian Filter after GaussianSmoothing
CODE gaussian+laplacian
myfilter=fspecial('gaussian',[3,3],0.5);%generating gaussian mask figure,imshow(imfilter(a22,myfilter,'replicate'));% filtering with gaussian mask >> w=fspecial('laplacian',0)
w =
0 1 0 1 -4 1 0 1 0
>> a22=im2uint8(mat2gray(z)); % increasing the dynamic range of the image >> g5=a22-imfilter(a22,w,'replicate'); >> figure,imshow(g5) >> figure,subplot(3,3,1),imshow(a),title('Original Image'),subplot(3,3,2),imshow(z,
[]),title('Gaussian Smoothing'),subplot(3,3,3),imshow(g5,[]),title('Laplacian Filtering After Gaussian Smoothing')
>> figure,subplot(1,3,1),imshow(a),title('Original Image'),subplot(1,3,2),imshow(z,[]),title('Gaussian Smoothing'),subplot(1,3,3),imshow(g5,[]),title('Laplacian Filtering After Gaussian Smoothing')
Gaussian smoothing with different sigma values + Laplacian Filter
CODE>> myfilter=fspecial('gaussian',[r,c],0.1);
%using a sigma value of 0.1 to generate gaussian kernel
>> z=imfilter(a22,myfilter,'replicate');>> g5=a22-imfilter(a22,w,'replicate');>> myfilter=fspecial('gaussian',[r,c],0.9);>> z=imfilter(a22,myfilter,'replicate');
Laplacian Filter + Gaussian smoothing with different mask size
3 by 3 Mask
5 by 5 Mask
7 by 7 Mask 9 by 9 Mask
CODE
%using different filter mask sizefor r=3:2:9;for c=3:2:9;myfilter=fspecial('gaussian',[r,c]);z=imfilter(a22,myfilter,'replicate');w=fspecial('laplacian',0); a22=im2uint8(mat2gray(z));g5=a22-imfilter(a22,w,'replicate');for n=1:4subplot(2,2,n),imshow(g5,[]);endendend
AVERAGE FILTERReplace each pixel by the average of pixels in a
square window surrounding this pixel.This has the effect of eliminating pixel values
which are unrepresentative of their surroundingsIt is used for reducing noise in an imageIt flattens local differences and reduces
sharpnessHowever, it blurs details and edgesIt is simple and easy to implement method of
smoothing images that is reducing the amount of intensity variations between one pixel and the next.
3 by 3 Average FilterOriginal image
5 by 5 Average FilterOriginal image
9 by 9 Average FilterOriginal image
11 by 11 Average FilterOriginal image
Code AVERAGE FILTER >> w=fspecial('average',[3 3])
w =
0.1111 0.1111 0.1111 0.1111 0.1111 0.1111 0.1111 0.1111 0.1111
>> gs=imfilter(a,w,'replicate'); >> figure,imshow(gs),title('Image After An Average Filter Is Applied')
>> s=fspecial('average',[5 5])
s =
0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 0.0400 >> gs=imfilter(a,s,'replicate'); >> figure,imshow(gs),title('Image After An Average 5 by 5 Filter Is Applied') >> s=fspecial('average',[11,11]); >> gs=imfilter(a,s,'replicate'); >> figure,imshow(gs),title('Image After An Average 11 by 11 Filter Is Applied')
Mask SizeMasks are usually chosen to have odd
dimensions to provide a centre pixel location. The output is written to that pixel.
Larger filters do more smoothing but also provides more blurring.
The low frequency response becomes more pronounced as the filter is increased
Larger filters removes noise but it also removes detailed information from edged and other image features.
Median FilterIs a non-linear filtering technique often used to
remove noise with laplacian distribution.The main idea of the median filter is to run through
entry by entry replacing each entry with the median of neighbouring entries.
It is used in reducing impulse or salt and pepper noise
It is useful in preserving edges in an image while reducing noise
Can smooth pixels whose values differ significantly from their surroundings without affecting other pixels.
3 by 3 For loop Median FilterOriginal image
Code >> a=imread('ultra.jpg'); size(a)
ans =
1345 1741 3
>> a=rgb2gray(a); >> %pad the matrix with zeros on all sides >> newA=zeros(size(a)+2); >> b=zeros(size(a)); >> %copy the original image matrix to padded matrix >> for x=1:size(a,1) for y=1:size(a,2) newA(x+1,y+1)=a(x,y); end end >> for i=1:size(newA,1)-2 for j=1:size(newA,2)-2 window=zeros(9,1); inc=1; for x=1:3 for y=1:3 window(inc)=newA(i+x-1,j+y-1);% first window selected inc=inc+1; end end med=sort(window); %place the median element in the output matrix b(i,j)=med(5);% the fifth element will be the middle element place that element in the output matrix end end >> %convert the output matrix to 0-255 range image type >> b=uint8(b); >> figure,imshow(b),title('Image After Median Filtering'); >> figure,imshow(a),title('Original Image')
3 by 3 filter with Matlab FunctionOriginal image
5 by 5 Median FilterOriginal image
7 by 7 Median FilterOriginal image
9 by 9 Median FilterOriginal image
Code% applying median filtering with matlab built in
functiongm=medfilt2(a,'symmetric');% symmetric is similar
to replicate, defining how you want to pad the imagefigure,imshow(gm),title('Image after Median filter
with Matlab built in function')gm=medfilt2(a,[5 5],'symmetric');figure,imshow(gm,[]),title('Image after 5*5 Matlab
Median Filter')gm=medfilt2(a,[7 7],'symmetric');figure,imshow(gm,[])gm=medfilt2(a,[9 9],'symmetric');figure,imshow(gm,[])
Unsharp FilterIt is a simple sharpening operator which
derives its name from the fact that it enhances edges via a procedure which subtracts an unsharp or smoothed version of the image from the original image.
Unsharp masking produces an edge image g(x,y) from an input image f(x,y).
g(x,y)=f(x,y)-fsmooth(x,y).Sharpening can help to emphasize texture and
detail and is critical when post-processing most digital images.
Sharpening the ImageOriginal image
Code%using a Sharpen Filter Maskce=fspecial('unsharp')cf=imfilter(a,ce,'corr','symmetric');% corr is
correlatingfigure,imshow(cf,[]),title('Image After using
Unsharp Mask')
Smoothing before Sharpening
Code% trying smoothing before sharpening the image by using a
gaussian filtercx=fspecial('gaussian',[3 3],0.5);cff=imfilter(a,cx,'conv','replicate');cx2=fspecial('unsharp');cff2=imfilter(cff,cx2,'conv','replicate');subplot(2,2,4),imshow(cff2,[]),title('Smoothing Image
Before Sharpening')sharpmore2=imfilter(cff2,cx2,'replicate');figure,imshow(sharpmore2,[]),title('Excessive Sharpening
after Smoothing')cff3=imfilter(cff2,cx,'replicate');sharpmore3=imfilter(cff3,cx2,'replicate');figure,subplot(1,2,1),imshow(sharpmore2,
[]),title('Excessive Sharpening after Smoothing is Applied Before ist Sharp Mask'),subplot(1,2,2),imshow(sharpmore3),title('Excessive Sharpening After Smoothing After Ist Sharp Mask Applied')
Smoothing before Sharpening by choosing a kernel independent of
Matlab
Code %Alternative Way of Sharpening the Image subplot(2,2,1),imshow(a),title('Original Ultrasound'); gaussianfilter=[1 4 7 4 1;4 20 33 20 4; 7 33 55 33 7;4 20 33 20 4;1 4 7
4 1];% choosing own weighted kernel gaussianfilter=gaussianfilter/sum(sum(guassianfilter));%normalizing gaussianfilter=gaussianfilter/sum(sum(gaussianfilter)); gaussianUltra=imfilter(a,gaussianfilter); subplot(2,2,2),imshow(gaussianUltra), title('Gaussian Ultra sound'); edgefilter=[-1,-1,-1;8,-1,-1;-1,-1,-1] edgeultra=imfilter(gaussianUltra,edgefilter); subplot(2,2,3),imshow(edgeultra); title('Edges from Blurred Ultrasound'); sharpultra=gaussianUltra+edgeultra; subplot(2,2,4),imshow(sharpultra); title('Sharp Ultrasound(sharper than original');
Disk FilterIs simple a circular averaging filterIt does the same as the average filter
mentioned earlier.The radius controls how big an area the
operator should locate when spreading pixels.
Original image
Code % using a disk filter on the imagecc=fspecial('disk')c3=imfilter(a,cc,'conv','replicate');figure,imshow(c3,[]),title('Image After using a
Disk Mask')
Changing Radius values in Disk Filtering
Radius of 2
Radius of 4
Radius of 6
Radius of 6
Radius of 18
Radius of 16
Radius of 14
Radius of 12
Code for r=2:2:8cs=fspecial('disk',r); fg=imfilter(a,cs,'conv','replicate');% conv refers to convolution for ss=1:4subplot(2,2,ss),imshow(fg,[])endend
for r=12:2:18cs=fspecial('disk',r); fg=imfilter(a,cs,'conv','replicate'); for ss=1:4subplot(2,2,ss),imshow(fg,[])endend
Sobel FilterThe sobel operator is a discrete
differentiation operator, computing an approximation of the gradient of the image intensity function.
It is based on convolving the image with a small, separable and integer valued filter in the horizontal and vertical direction.
The final step involves approximating the gradient magnitude.
Vertical and Horizontal Gradient Sobel Images
Vertical and Horizontal Sobel Image resulted from Subtracting sobel normalized images from original
images
Code % now using a sobel Mask cr=fspecial('sobel') % generate a vertical gradient mask cr=
1 2 1 0 0 0 -1 -2 -1
cr2=imfilter(a,cr,'conv','replicate'); figure,imshow(cr2,[]) crr=cr‘ % will give a horizontal gradient mask cr3=imfilter(a,crr,'conv','replicate'); figure,subplot(1,2,1),imshow(cr2,[]),title('Normalized Vertical gradient
from Sobel operator'),subplot(1,2,2),imshow(cr3,[]),title('Normalized Horizontal gradient from Sobel operator')
cr4=im2uint8(mat2gray(a)); cr5=imfilter(cr4,cr,'conv','replicate'); cr6=cr4-cr5; % to get the final image cr5=imfilter(cr4,crr,'conv','replicate'); cr7=cr4-cr5; figure,subplot(1,2,1),imshow(cr6,[]),title('Vertical Sobel mask Applied') subplot(1,2,2),imshow(cr7,[]),title('Horizontal Sobel Mask Applied')
Sobel Gradient Magnitude & Direction using Gmag Function
Code%Finding the image gradient[gmag,gdir]=imgradient(a,'sobel');figure,imshowpair(gmag,gdir,'montage');title('Gradient Magnitude,Gmag(left), and
Gradient Direction,Gdir(right),using Sobel Method')
imtool(gmag)cd=im2uint8(gmag);
Magnitude of Sobel Gradient directly from the Vertical and Horizontal components
code a=imread('ultra.jpg'); >> a=rgb2gray(a); >> hy=fspecial('sobel'); >> hx=hy'; >> a=im2uint8(mat2gray(a)); >> gx=imfilter(a,hx); %x component of sobel gradient >> gy=imfilter(a,hy); %y component of sobel gradient >> igx2=im2double(gx); >> igy2=im2double(gy); >> gmag=hypot(igx2,igy2); %HYPOT Robust computation of the
square root of the sum of squares
>> figure,imshow(gmag) >> a=im2double(a); >> finalimage=a-gmag; %retrieving final image >> figure,imshow(finalimage);
Prewitt FilterThe prewitt operator is a discrete
differentiation operator, computing an approximation of the gradient of the image intensity function.
At each point in the image, the result of the prewitt operator is either the corresponding gradient vector or the norm of this vector.
The prewitt operator is based on convolving the image with small separable and integer valued filter in horizontal and vertical direction.
Used to detect edges.
Vertical and Horizontal Gradient Prewitt Images
Prewitt gradient Magnitude
code >> hy=fspecial('prewitt') hy =
1 1 1 0 0 0 -1 -1 -1 >> hx=hy'; >> a=im2uint8(mat2gray(a)); >> gx=imfilter(a,hx); %x component prewitt gradient >> gy=imfilter(a,hy); %y component of prewitt gradient >> igx2=im2double(gx); igy2=im2double(gy); gmag=hypot(igx2,igy2); figure,imshow(gmag) a=im2double(a); finalimage=a-gmag; figure,imshow(finalimage);