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

Image Segmentation using K Means Clustering

Last Updated : 09 Feb, 2023
Summarize
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
K-Means Clustering using PySpark Python
In this tutorial series, we are going to cover K-Means Clustering using Pyspark. K-means is a clustering algorithm that groups data points into K distinct clusters based on their similarity. It is an unsupervised learning technique that is widely used in data mining, machine learning, and pattern recognition. The algorithm works by iteratively assi
4 min read
ML | Determine the optimal value of K in K-Means Clustering
Prerequisite: K-Means Clustering | IntroductionThere is a popular method known as elbow method which is used to determine the optimal value of K to perform the K-Means Clustering Algorithm. The basic idea behind this method is that it plots the various values of cost with changing k. As the value of K increases, there will be fewer elements in the
2 min read
Difference between K means and Hierarchical Clustering
k-means is method of cluster analysis using a pre-specified no. of clusters. It requires advance knowledge of 'K'. Hierarchical clustering also known as hierarchical cluster analysis (HCA) is also a method of cluster analysis which seeks to build a hierarchy of clusters without having fixed number of cluster. Main differences between K means and Hi
2 min read
K-Means Clustering in R Programming
K Means Clustering in R Programming is an Unsupervised Non-linear algorithm that cluster data based on similarity or similar groups. It seeks to partition the observations into a pre-specified number of clusters. Segmentation of data takes place to assign each training example to a segment called a cluster. In the unsupervised algorithm, high relia
3 min read
ML | Mini Batch K-means clustering algorithm
Prerequisite: Optimal value of K in K-Means Clustering K-means is one of the most popular clustering algorithms, mainly because of its good time performance. With the increasing size of the datasets being analyzed, the computation time of K-means increases because of its constraint of needing the whole dataset in main memory. For this reason, sever
6 min read
Difference between K means and K medoids Clustering
Clustering is the most basic form of data grouping in data analysis as well as in machine learning; the process involves putting the given set of objects into various groups. In which the objects in any single group will be much closer to one another than the objects belonging to other groups. Facilitating the process of clustering, there are sever
5 min read
Is K Means Clustering Considered Supervised or Unsupervised Machine Learning?
Answer: K-means clustering is considered an unsupervised machine learning algorithm. This categorization is because it does not rely on labeled input data for training; instead, it organizes data into clusters based on inherent similarities without any predefined labels.In this article we will explore K-Means Clustering in Machine Learning Unsuperv
2 min read
What is the Most Efficient K-Means Clustering Package in R?
K-means clustering is one of the most popular unsupervised machine learning algorithms used for grouping data points into a specified number of clusters. Each data point is assigned to the cluster with the nearest mean, serving as a prototype of the cluster. In R, several packages provide implementations of the K-means algorithm, each with differen
6 min read
K means Clustering - Introduction
K-Means Clustering is an Unsupervised Machine Learning algorithm, which groups the unlabeled dataset into different clusters. The article aims to explore the fundamentals and working of k mean clustering along with the implementation. Table of Content What is K-means Clustering?What is the objective of k-means clustering?How k-means clustering work
9 min read
Image Segmentation using Python's scikit-image module
The process of splitting images into multiple layers, represented by a smart, pixel-wise mask is known as Image Segmentation. It involves merging, blocking, and separating an image from its integration level. Splitting a picture into a collection of Image Objects with comparable properties is the first stage in image processing. Scikit-Image is the
14 min read
DBSCAN Clustering in ML | Density based clustering
Clustering analysis or simply Clustering is basically an Unsupervised learning method that divides the data points into a number of specific batches or groups, such that the data points in the same groups have similar properties and data points in different groups have different properties in some sense. It comprises many different methods based on
7 min read
Difference between CURE Clustering and DBSCAN Clustering
Clustering is a technique used in Unsupervised learning in which data samples are grouped into clusters on the basis of similarity in the inherent properties of the data sample. Clustering can also be defined as a technique of clubbing data items that are similar in some way. The data items belonging to the same clusters are similar to each other i
2 min read
Difference Between Agglomerative clustering and Divisive clustering
Hierarchical clustering is a popular unsupervised machine learning technique used to group similar data points into clusters based on their similarity or dissimilarity. It is called "hierarchical" because it creates a tree-like hierarchy of clusters, where each node represents a cluster that can be further divided into smaller sub-clusters. There a
5 min read
Image segmentation using Morphological operations in Python
If we want to extract or define something from the rest of the image, eg. detecting an object from a background, we can break the image up into segments in which we can do more processing on. This is typically called Segmentation. Morphological operations are some simple operations based on the image shape. It is normally performed on binary images
3 min read
Image Segmentation Using TensorFlow
Image segmentation refers to the task of annotating a single class to different groups of pixels. While the input is an image, the output is a mask that draws the region of the shape in that image. Image segmentation has wide applications in domains such as medical image analysis, self-driving cars, satellite image analysis, etc. There are differen
7 min read
Object Detection vs Object Recognition vs Image Segmentation
Object Recognition: Object recognition is the technique of identifying the object present in images and videos. It is one of the most important applications of machine learning and deep learning. The goal of this field is to teach machines to understand (recognize) the content of an image just like humans do. Object Recognition Using Machine Learni
5 min read
Image Segmentation with Mask R-CNN, GrabCut, and OpenCV
Image segmentation plays a crucial role in computer vision tasks, enabling machines to understand and analyze visual content at a pixel level. It involves dividing an image into distinct regions or objects, facilitating object recognition, tracking, and scene understanding. In this article, we explore three popular image segmentation techniques: Ma
13 min read
PSPNet (Pyramid Scene Parsing Network) for Image Segmentation
Within the intricate landscape of semantic segmentation, the Pyramid Scene Parsing Network or PSPNet has emerged as a formidable architecture by showcasing unparalleled performance in deciphering intricate scenes. In this article, we will discuss about PSPNet and implement it. What is Semantic Segmentation?Semantic segmentation stands as a cutting-
14 min read
Image Segmentation with Watershed Algorithm - OpenCV Python
Image segmentation is a fundamental computer vision task that involves partitioning an image into meaningful and semantically homogeneous regions. The goal is to simplify the representation of an image or make it more meaningful for further analysis. These segments typically correspond to objects or regions of interest within the image. Watershed A
9 min read
Explain Image Segmentation : Techniques and Applications
Image segmentation is one of the key computer vision tasks, It separates objects, boundaries, or structures within the image for more meaningful analysis. Image segmentation plays an important role in extracting meaningful information from images, enabling computers to perceive and understand visual data in a manner that humans understand, view, an
9 min read