Change language

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.



Learn programming in R: courses


Best Python online courses for 2022


Best laptop for Fortnite


Best laptop for Excel


Best laptop for Solidworks


Best laptop for Roblox


Best computer for crypto mining


Best laptop for Sims 4


Latest questions


psycopg2: insert multiple rows with one query

12 answers


How to convert Nonetype to int or string?

12 answers


How to specify multiple return types using type-hints

12 answers


Javascript Error: IPython is not defined in JupyterLab

12 answers



Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method