Dilation and Erosion
Structuring element
It is a small binary image or a small matrix of pixels, each with value of zero or one.
It is positioned at all possible locations in the image and it is compared with the corresponding neighborhood of pixels.
Some operations test whether the element ‘fits’ within the neighborhood, while others test whether it “hits” or intersects the neighborhood.
When a structuring element is placed in a binary image, it is said to ‘fit’ the image if, for each of its pixels set to 1 , the corresponding image pixel is same. Similarly, a structuring element is said to “hit” the image if, at least for one of its pixels set 1, the corresponding image pixel is same.
Zero-valued pixels of the structuring element are ignored.

Dilation and Erosion
Let A(x,y) be a binary image and B(x,y) be a structuring element with ones in all locations(x,y).
Here, the Erosion of A(x,y) by B(x,y) produces a new binary image g(x,y) where if the structuring element fits the image A(x,y) then its origin at the image ‘g’ is set to 1 i.e. g(x,y) = 1 otherwise g(x,y) = 0 which is repeated for all pixel coordinates (x,y).
In words, if the structuring element fully matches then g(x,y) =1, some match then g(x,y) =0 and no match the g(x,y) =0.
For grayscale erosion, the origin pixel is replaced by greatest element(infimum value).
Erosion is represented as:



Here, the Dilation of A(x,y) by B(x,y) produces a new binary image g(x,y) where if the structuring element fits the image A(x,y) then its origin at the image ‘g’ is set to 1 i.e. g(x,y) = 1 and if structuring element hits the image A(x,y) then its origin at the image ‘g’ is set to 1 i.e. g(x,y) = 1 otherwise g(x,y) = 0 which is repeated for all pixel coordinates (x,y) .
In words, if the structuring element fully matches then g(x,y) =1, some match then g(x,y) =1 and no match the g(x,y) =0.
For grayscale dilation, the origin pixel is replaced by least element (supremum value).
Dilation is represented as:



Dilate = NOT[erode]
Erode = NOT[dilate]
But erosion is not the inverse of dilation.
Opening and Closing
It is used for smoothing without size change.
It is used for enhancement or detection.
Opening:
It removes small 1-regions.
It involves erosion followed by dilation.
Open(A,B) = dilate(erode(A,B),B)

Closing:
It removes small 0-regions.
It involves dilation followed by erosion.
Close(A,B) = erode(dilate(A,B),B)

Note: Opening and Closing are dual, but not inverses of each other.