Matlab – Opening and Closing

Opening Manual Way

Before this, i have share some knowledge on erosion and dilation. This knowledge is necessary to continue with this topic which is Opening and Closing. The purpose of opening is to smoothens contours, nelarges narrow gaps and eliminates thin protrusions and ridges. On the other hand, closing will help to fills narrow gaps, holes and small breaks. In this post, i will explain some general idea of opening and closing and show to you some example Matlab source code for opening and closing.

Firstly, i will focus on opening. Opening is like smoothing from the inside. There is simple rule of thumb which you need to remember for opening.Opening is erosion followed by dilation. Below is the Matlab source code for Opening.

a=[0 0 0 0 0 0 0 0;…
0 1 1 1 0 0 0 0;…
0 1 1 1 0 0 0 0;…
0 1 1 1 1 0 0 0;…
0 0 0 1 1 1 1 0;…
0 0 0 0 1 1 1 0;…
0 0 0 0 1 1 1 0;…
0 0 0 0 0 0 0 0];

 

b=[0 1 0;1 1 1;0 1 0];

 

c=imerode(a,b);
d=imdilate(c,b);

 

subplot(2,2,1),imshow(a);subplot(2,2,2),imshow(b);
subplot(2,2,3),imshow(c);subplot(2,2,4),imshow(d);

 

Opening Matlab

 

This Matlab source code has been tested and should work successfully. You will be able to see four images after execution of this source code. The original image a, structuring element b, c is erosion of image a and structuring element b while d is the result of erosion being dilated with the structuring element b.

Figure below shows how opening is being done using manual way.

Opening Manual Way

 

Closing is like smoothing from the outside. The rule is vice versa from opening. The rule of closing is dilation followed by erosion. Do not get confused between both two opening and closing.

a=[0 0 0 0 0 0 0;…
0 1 1 1 0 1 0;…
0 1 0 1 0 0 0;…
0 1 1 1 0 1 0;…
0 0 0 0 0 0 0;…
0 1 1 1 1 0 0;…
0 0 0 0 0 0 0];

 

b=[0 1 0;…
1 1 1;…
0 1 0];

 

c=imdilate(a,b);
d=imerode(c,b);

 

subplot(2,2,1),imshow(a);subplot(2,2,2),imshow(b);
subplot(2,2,3),imshow(c);subplot(2,2,4),imshow(d);

 

Closing Matlab

 

This Matlab Closing source code has been tested and should work successfully. You will be able to see four images after execution of this closing source code. The original image a, structuring element b, c is dilation of image a with structuring element b while d is the result of dilation being erode with the structuring element b.

Figure below shows how opening is being done using manual way.

Closing Manual Way (Theoretical)

 

Take note that you may find there is difference between opening and closing using Matlab and manual (theoretical) way. It’s perfectly normal. This is because the theoretical definition of erode and dilate is difference with Matlab definition. You can verify this by using Matlab product help and look for definition of imerode and imdilate. You may find Matlab definition of erosion and dilation is tolerating much than the theoretical way.

Leave a Reply

Your email address will not be published. Required fields are marked *