Skip to content

Morphological Operation 1) Opening 2)Closing 3) Erosion 4) Dilation 5) Boundary Extraction

% morphdemo.m
% demonstration of morphological operators
clc;
clear all; 
close all;
load p64int.txt; % 64 x 64 gray scale image
V=[80:168];
x=ones(size(p64int))-ismember(p64int,V);
figure(1),clf,
subplot(231),imagesc(x),colormap(‘gray’)
% dialation and erosion
disp(‘***********************************’)
disp(‘0 – square (default)’);
disp(‘1 – circle’);
disp(‘2 – lower triangle’);
choice=input(‘Enter your structure element choice: ‘);
if isempty(choice), choice=0; end
switch choice
case 0                    % rectangle structure element
   dimen=input(‘enter dimension of the rectangle structure element (default 3): ‘);
   if isempty(dimen), dimen=3; end
   S=ones(dimen);
case 1                    % circle element
   r=input(‘enter radius of the circle structure element (default = 2): ‘);
   if isempty(r), r=2; end
   S=zeros(2*r+1); % a square of 2r+1
   for i=1:2*r+1,
      for j=1:2*r+1,
         if (i-r-1)^2+(j-r-1)^2 <=r^2; S(i,j)=1;
         end
      end
   end
case 2% triangular shape
   S=[1 0 0; 1 0 0; 1 1 1];
end
% figure(2),clf,imagesc(S);,colormap(‘gray’)
disp(‘Dilation and Erosion’)
% using command dilate and erode
y1=dilate(x,S);
figure(1),subplot(232),imagesc(y1),title(‘dilation’)
y2=erode(x,S);
figure(1),subplot(233),imagesc(y2),title(‘erosion’)
%pause
disp(‘Opening and Closing’)
% opening and closing
y3=dilate(y2,S);  % opening
figure(1),subplot(234),imagesc(y3),title(‘opening’)
y4=erode(y1,S); % closing
figure(1),subplot(235),imagesc(y4),title(‘closing’)
%pause
% boundary extraction
beta=x-double(erode(x,S));

figure(1),subplot(236),imagesc(beta),title(‘boundary extraction’)

Output
Morphological Operations

Leave a Reply

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

error: Content is protected !!