You can use morphological opening to remove small objects from an image while preserving the shape and size of larger objects in the image.
In this example, you use morphological opening on an image of a circuitboard to remove all the circuit lines from the image. The output image contains only the rectangular shapes of the microchips.
You can use the
imopen function to perform erosion and dilation in one step.
Read the image into the workspace, and display it.
BW1 = imread('circbw.tif'); figure imshow(BW1)
Create a structuring element. The structuring element should be large enough to remove the lines when you erode the image, but not large enough to remove the rectangles. It should consist of all
1s, so it removes everything but large contiguous patches of foreground pixels.
SE = strel('rectangle',[40 30]);
Open the image.
BW2 = imopen(BW1, SE); imshow(BW2);
You can also perform erosion and dilation sequentially.
Erode the image with the structuring element. This removes all the lines, but also shrinks the rectangles.
BW3 = imerode(BW1,SE); imshow(BW3)
To restore the rectangles to their original sizes, dilate the eroded image using the same structuring element,
BW4 = imdilate(BW3,SE); imshow(BW4)
By performing the operations sequentially, you have the flexibility to change the structuring element. Create a different structuring element, and dilate the eroded image using the new structuring element.
SE = strel('diamond',15); BW5 = imdilate(BW3,SE); imshow(BW5)