Matlab | Erosion of an Image (original) (raw)

Last Updated : 30 Nov, 2021

Morphology is known as the broad set of image processing operations that process images based on shapes. It is also known as a tool used for extracting image components that are useful in the representation and description of region shape.

The basic morphological operations are:

In this article, we will be discussing Erosion.

Erosion:

Approach:

Example:

MATLAB `

% Matlab code for Erosion % read image I=imread('lenna.png');

% convert to binary
I=im2bw(I);

% create structuring element
se=ones(5, 5);

% store number of rows % in P and number of columns in Q.
[P, Q]=size(se);

% create a zero matrix of size I.
In=zeros(size(I, 1), size(I, 2));

for i=ceil(P/2):size(I, 1)-floor(P/2) for j=ceil(Q/2):size(I, 2)-floor(Q/2)

    % take all the neighbourhoods.
    on=I(i-floor(P/2):i+floor(P/2), j-floor(Q/2):j+floor(Q/2)); 

    % take logical se
    nh=on(logical(se)); 
  
    % compare and take minimum value of the neighbor 
    % and set the pixel value to that minimum value. 
    In(i, j)=min(nh(:));      
end

end

imshow(In);

`

Output:

figure: Input image

figure: Output Image

Let's take another image to perform Erosion and here we use different MATLAB functions.

Syntax:

Example:

Matlab `

% MATLAB code for Erison % read the image. k=imread("erosion.png");

%define the structuring element. SE=strel('disk',5);

%apply the erosion operation. e=imerode(k,SE);

%display all the images. imtool(k,[]); imtool(e,[]);

%see the effective reduction in org,image imtool(k-e,[]);

`

Output:

Figure: Left: Original image, Right: Eroded image

Figure: Output image

Code explanation:

The last image shows the extent to which the original image got eroded. We have used the Structuring element of disk-shaped and the image we used is also circular in shape. This gives us the very desired output to understand erosion.