Morphological Transformations OpenCV Python Tutorial

In this OpenCV with Python tutorial, we're going to cover Morphological Transformations. These are some simple operations that we can perform based on the image's shape.

These tend to come in pairs. The first pair we're going to talk about is Erosion and Dilation. Erosion is where we will "erode" the edges. The way these work is we work with a slider (kernel). We give the slider a size, let's say 5 x 5 pixels. What happens is we slide this slider around, and if all of the pixels are white, then we get white, otherwise black. This may help eliminate some white noise. The other version of this is Dilation, which basically does the opposite: Slides around, if the entire area isn't black, then it is converted to white. Here's an example:

The next pair is "opening" and "closing." The goal with opening is to remove "false positives" so to speak. Sometimes, in the background, you get some pixels here and there of "noise." The idea of "closing" is to remove false negatives. Basically this is where you have your detected shape, like our hat, and yet you still have some black pixels within the object. Closing will attempt to clear that up.

Two other options that aren't really useful for our case here are "tophat" and "blackhat:"

# It is the difference between input image and Opening of the image
cv2.imshow('Tophat',tophat)
# It is the difference between the closing of the input image and input image.
cv2.imshow('Blackhat',blackhat)

In the next tutorial, we're going to be discussing image gradients and edge detection.