matlabimage-processingimage-morphology

Matlab: Dilation operator does not return the desired output


Suppose we want to enlarge black region in a binary image using morphological dilation operator in Matlab. The desired output must be as below, but the given code generate a different image! enter image description here

bin = ones(10,10, 'uint8');
bin(3:8, 3:8) = 0;
bin([4 7], [4 7]) = 1;
nhood = [1 0 1; 
         0 0 0; 
         1 0 1];
dil = imdilate(bin, strel(nhood))
figure; 
subplot(1,2,1)
imshow(255*bin, 'InitialMagnification', 'fit')
subplot(1,2,2)
imshow(255*dil, 'InitialMagnification', 'fit')

Structuring element and original image are shown below:


Solution

  • In this case your structuring element is inverted i.e. [255, 0, 255;0, 0, 0; 255, 0, 255] will be used when you make black region as foreground.

    To get the result as shown in the video, you will have to use [0, 1, 0;1, 1, 1; 0, 1, 0] as a structuring element.

    Note: Normally, in morphological operation you take white region as the foreground and use structuring element to modify the foreground. But in this video he is using black region as foreground

    bin = ones(10,10, 'uint8');
    bin(3:8, 3:8) = 0;
    bin([4 7], [4 7]) = 1;
    nhood = [0 1 0; 
             1 1 1; 
             0 1 0];
    erode = imerode(bin, strel(nhood));
    dilate = imdilate(erode, strel(nhood));
    figure; 
    subplot(2,2,1)
    imshow(255*bin, 'InitialMagnification', 'fit')
    subplot(2,2,2)
    imshow(255*erode, 'InitialMagnification', 'fit')
    title('after erosion')
    subplot(2,2,3)
    imshow(255*dilate, 'InitialMagnification', 'fit')
    title('after dilation')
    

    enter image description here