Image segmentation using morphological operations in Python

Morphological operations — these are a few simple operations based on the shape of the image. This is usually done on binary images. The two main morphological operators — it is erosion and dilatation. For a basic understanding of expansion and erosion, refer to this

# Python program to convert an image using
# threshold.

import numpy as np

import cv2

from matplotlib import pyplot as plt

# Working with image using threshold 

img = cv2.imread ( `c4.jpg` )


gray = cv2.cvtColor (img, cv2.COLOR_BGR2GRAY)


ret, thresh = cv2.threshold (gray, 0 , 255 ,



cv2.imshow ( `image ` , thresh)


This output shows that the image is transformed using a thresholding operation when the foreground still contains some noise.

Now we need to remove any small white noise from the image, i.e. in the foreground. For this we can use morphological closure. To remove any small holes in the foreground object, we can use morphological closure. To get the background, we expand the image. The extension expands the object`s border to the background.

Let`s see the code:

# Noise removal with morphological
# close operation

kernel = np.ones (( 3 , 3 ), np.uint8)

closing = cv2.morphologyEx (thresh, cv2.MORPH_CLOSE,

kernel, iterations = 2 )

# Background area using dialing

bg = cv2.dilate (closing, kernel, iterations = 1 )

# Finding foreground

dist_transform = cv2.distanceTransform (closing, cv2.DIST_L2, 0 )

ret, fg = cv2.threshold (dist_transform, 0.02

  * dist_transform. max ( ), 255 , 0 )


cv2.imshow ( ` image` , fg)


From the output image we we can infer that small holes are removed by the close operation, and make sure that any area in the foreground in the result is indeed the foreground.