Mathematical Morphology – Opening and Closing, Top Hat, Black Hat, Gradient in OpenCV

We discussed dilation and erosion in previous article where we discussed that one expands the object pixels and the other shrinks them. What if we combine these operations? Fine these interesting details written below.

Opening

An erosion operation followed by dilation operation with the same structuring element is known as opening operation. An opening removes noise, narrow features and smooths object boundaries. It also maintains approximate size of the object. Something like this

```erode(motion,motion,Mat());
dilate(motion,motion,Mat());
```

Instead of using above code, use the key function to perform morphology transformations is morphologyEx which takes four argument as follow : src : Source (input) image dst: Output image operation: The kind of morphology transformation to be performed. Note that we have 5 alternatives: Opening: MORPH_OPEN : 2 Closing: MORPH_CLOSE: 3 Gradient: MORPH_GRADIENT: 4 Top Hat: MORPH_TOPHAT: 5 Black Hat: MORPH_BLACKHAT: 6 Opening can be invoked as follows.

```Mat ero(5,5,CV_8U,Scalar(1));
morphologyEx(motion,motion,MORPH_OPEN,ero);```

Closing

A dilation operation followed by an erosion operation with same structuring element. It fills in holes within an object which are close together.

```dilate(motion,motion,Mat());
erode(motion,motion,Mat());```
```Mat ero(5,5,CV_8U,Scalar(1));
morphologyEx(motion,motion,MORPH_CLOSE,ero);```

Mathematical Morphology – Opening and Closing Operation results :

Note: It is a common practice in most of applications to use closing followed by opening which clean up binary image data.

To find the difference between dilate and erosion use morphological gradient operation. It indicates the contrast intensity in the close neighborhood of that pixel. It is also useful for edge detection and segmentation applications.

`morphologyEx(motion,motion,MORPH_GRADIENT,ero);`

Top Hat

It is suitable to find difference between input image and its opening by some structure element. The top hat transform returns an image, containing those objects or elements of an input image that are smaller than the structure element and are brighter than their surroundings. Top-hat transforms are used for various image processing tasks, such as feature extraction, background equalization and image enhancement.

`morphologyEx(motion,motion,MORPH_TOPHAT,ero);`

Black Hat

It is suitable to find difference between input image and its closing by some structure element. The black transform returns an image, containing those objects or elements of an input image that are smaller than the structuring element, and are darker than their surroundings.

`morphologyEx(motion,motion,MORPH_BLACKHAT,ero);`

Mathematical Morphology – Gradient, Top Hat and Black Hat Operation results :

Thank you for reading my article. Would love to hear back from you related to improvements or suggestions coming from your side.