The Wayback Machine - https://web.archive.org/web/20240812095356/https://www.geeksforgeeks.org/image-segmentation-using-k-means-clustering/
Open In App

Image Segmentation using K Means Clustering

Last Updated : 09 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

 Image Segmentation: In computer vision, image segmentation is the process of partitioning an image into multiple segments. The goal of segmenting an image is to change the representation of an image into something that is more meaningful and easier to analyze. It is usually used for locating objects and creating boundaries. 

It is not a great idea to process an entire image because many parts in an image may not contain any useful information. Therefore, by segmenting the image, we can make use of only the important segments for processing. 

An image is basically a set of given pixels. In image segmentation, pixels which have similar attributes are grouped together. Image segmentation creates a pixel-wise mask for objects in an image which gives us a more comprehensive and granular understanding of the object.

Uses: 

  1. Used in self-driving cars. Autonomous driving is not possible without object detection which involves segmentation.
  2. Used in the healthcare industry. Helpful in segmenting cancer cells and tumours using which their severity can be gauged.

There are many more uses of image segmentation.

In this article, we will perform segmentation on an image of the monarch butterfly using a clustering method called K Means Clustering.

K Means Clustering Algorithm:

K Means is a clustering algorithm. Clustering algorithms are unsupervised algorithms which means that there is no labelled data available. It is used to identify different classes or clusters in the given data based on how similar the data is. Data points in the same group are more similar to other data points in that same group than those in other groups. 

K-means clustering is one of the most commonly used clustering algorithms. Here, k represents the number of clusters.

Let’s see how does K-means clustering work –

  1. Choose the number of clusters you want to find which is k.
  2. Randomly assign the data points to any of the k clusters.
  3. Then calculate the center of the clusters.
  4. Calculate the distance of the data points from the centers of each of the clusters.
  5. Depending on the distance of each data point from the cluster, reassign the data points to the nearest clusters.
  6. Again calculate the new cluster center.
  7. Repeat steps 4,5 and 6 till data points don’t change the clusters, or till we reach the assigned number of iterations.

Requirements:

  • Make sure you have Python, Numpy, Matplotlib and OpenCV installed.

Code: Read in the image and convert it to an RGB image.

python3




import numpy as np
import matplotlib.pyplot as plt
import cv2
 
%matplotlib inline
 
# Read in the image
image = cv2.imread('images/monarch.jpg')
 
# Change color to RGB (from BGR)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
 
plt.imshow(image)


Now we have to prepare the data for K means. The image is a 3-dimensional shape but to apply k-means clustering on it we need to reshape it to a 2-dimensional array.

Code: 

python3




# Reshaping the image into a 2D array of pixels and 3 color values (RGB)
pixel_vals = image.reshape((-1,3))
 
# Convert to float type
pixel_vals = np.float32(pixel_vals)


Now we will implement the K means algorithm for segmenting an image. 

Code:  Taking k = 3, which means that the algorithm will identify 3 clusters in the image.

python3




#the below line of code defines the criteria for the algorithm to stop running,
#which will happen is 100 iterations are run or the epsilon (which is the required accuracy)
#becomes 85%
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.85)
 
# then perform k-means clustering with number of clusters defined as 3
#also random centres are initially choosed for k-means clustering
k = 3
retval, labels, centers = cv2.kmeans(pixel_vals, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
 
# convert data into 8-bit values
centers = np.uint8(centers)
segmented_data = centers[labels.flatten()]
 
# reshape data into the original image dimensions
segmented_image = segmented_data.reshape((image.shape))
 
plt.imshow(segmented_image)


Output: 

Now if we change the value of k to 6, we get the following Output:

As you can see with an increase in the value of k, the image becomes clearer and distinct because the K-means algorithm can classify more classes/cluster of colors. K-means clustering works well when we have a small dataset. It can segment objects in images and also give better results. But when it is applied on large datasets (more number of images), it looks at all the samples in one iteration which leads to a lot of time being taken up. 



Previous Article
Next Article

Similar Reads

Image Segmentation Using Fuzzy C-Means Clustering
This article delves into the process of image segmentation using Fuzzy C-Means (FCM) clustering, a powerful technique for partitioning images into meaningful regions. We'll explore the fundamentals of FCM, its advantages over traditional methods, and provide a step-by-step guide to implementing FCM for image segmentation using Python. By the end of
7 min read
Image compression using K-means clustering
Prerequisite: K-means clustering The internet is filled with huge amounts of data in the form of images. People upload millions of pictures every day on social media sites such as Instagram, and Facebook and cloud storage platforms such as google drive, etc. With such large amounts of data, image compression techniques become important to compress
6 min read
Image Segmentation Using Mean Shift Clustering
Image segmentation is the process of partitioning an image into multiple segments or regions to simplify its representation and facilitate analysis. The goal is to group pixels with similar characteristics, such as color, texture, or intensity, into coherent and meaningful segments. The use of mean shift clustering (MSC) in image segmentation is a
7 min read
Image Segmentation By Clustering
Segmentation By clustering It is a method to perform Image Segmentation of pixel-wise segmentation. In this type of segmentation, we try to cluster the pixels that are together. There are two approaches for performing the Segmentation by clustering. Clustering by MergingClustering by Divisive Clustering by merging or Agglomerative Clustering: In th
4 min read
Semantic Segmentation vs Instance Segmentation
Image segmentation task involves partitioning the image into many segments or regions based on color, intensity, texture or spatial proximity. In this article, we are going to understand semantic segmentation, instance segmentation and their key differences. What is Image Segmentation?Image segmentation is a computer vision task that aims at identi
5 min read
Analysis of test data using K-Means Clustering in Python
This article demonstrates an illustration of K-means clustering on a sample random data using open-cv library. Pre-requisites: Numpy, OpenCV, matplot-lib Let's first visualize test data with Multiple Features using matplot-lib tool. # importing required tools import numpy as np from matplotlib import pyplot as plt # creating two test data X = np.ra
2 min read
K means clustering using Weka
In this article, we are going to see how to use Weka explorer to do simple k-mean clustering. Here we will use sample data set which is based on iris data that is available in ARFF format. There are 150 iris instances in this dataset. Before starting let's have a small intro about clustering and simple-k. Note: This article assumes that the data ha
3 min read
Clustering Text Documents using K-Means in Scikit Learn
Clustering text documents is a typical issue in natural language processing (NLP). Based on their content, related documents are to be grouped. The k-means clustering technique is a well-liked solution to this issue. In this article, we'll demonstrate how to cluster text documents using k-means using Scikit Learn. K-means clustering algorithm The k
2 min read
K-Means clustering on the handwritten digits data using Scikit Learn in Python
K - means clustering is an unsupervised algorithm that is used in customer segmentation applications. In this algorithm, we try to form clusters within our datasets that are closely related to each other in a high-dimensional space. In this article, we will see how to use the k means algorithm to identify the clusters of the digits. Load the Datase
5 min read
Analyzing Decision Tree and K-means Clustering using Iris dataset
Iris Dataset is one of best know datasets in pattern recognition literature. This dataset contains 3 classes of 50 instances each, where each class refers to a type of iris plant. One class is linearly separable from the other 2 the latter are NOT linearly separable from each other. Attribute Information:Sepal Length in cmSepal Width in cmPetal Len
5 min read
three90RightbarBannerImg