The Wayback Machine - https://web.archive.org/web/20240727001539/https://www.geeksforgeeks.org/image-segmentation-using-mean-shift-clustering/
Open In App

Image Segmentation Using Mean Shift Clustering

Last Updated : 10 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

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 well-known method in computer vision that divides an image into meaningful zones according to color and space.

In this article, we’ll discuss the implementation of image segmentation by mean shift clustering.

image-segmentation-using-mean-shift-clustering-(1)

Image Segmentation Using Mean Shift Clustering

What is mean shift clustering?

Mean shift clustering is a method used to find clusters in data without specifying the number of clusters beforehand. Mean shift clustering is a non-parametric, reiterative algorithm that seeks to identify groups in a dataset by discovering the sharper peaks in a density function, when, unlike some clustering algorithms, it does not require a piece of prior knowledge on the number of categories.

Why to use mean shift clustering for image segmentation?

Mean shift clustering is used for image segmentation because it is a non-parametric, unsupervised method that effectively identifies the modes or high-density regions of data, which correspond to the different segments in an image. By iteratively shifting data points towards the average of points within a given window, mean shift clustering can discover arbitrarily shaped clusters without assuming a specific number of clusters beforehand. This makes it particularly suitable for image segmentation, where the goal is to partition the image into meaningful regions based on pixel intensity and color. The method’s ability to handle complex structures and its robustness to noise further enhance its effectiveness in accurately segmenting images.

Steps for Image Segmentation Using Mean Shift Clustering:

  1. Comprehend Mean Shift Clustering: Mean Shift is a non-parametric technique for clustering which is aimed at finding modes of density function. It essentially shifts data points to go towards an average of points situated in a particular vicinity before subsequently moving towards regions characterized by a higher density through a succession of iterations.
  2. Preprocess the image: Change the color space so that the image better reflects how people perceive colors (e.g., from RGB to Lab* or HSV). It is also optional to get a read of noise by spatial smoothing (e.g., Gaussian blur).
  3. Feature Space Construction: Develop a feature space combining color and spatial information. Assuming an image of size ? × ? (W×H) with 3 color channels (e.g., RGB), every pixel can be represented as a five-dimensional vector [ ?, ?, ?, ?, ? ] [R, G, B,x,y], where ( ?, ? ) (x,y) are pixel coordinates.
  4. Mean Shift Clustering:Apply Mean Shift clustering in space slightly limited feature space – a way of grouping similar pixels based on color and spatial proximity (Wikipedia).
  5. Label Assignment: To each pixel assign the cluster center that it converged to. This second step makes it possible to divide the image into regions according to the previously designed clusters.
  6. Smoothen the Image: After the segmentation has been post-processed, you may smoothen the segmented image to either reduce the number of small regions which appear to be false or refine its boundaries.

Image taken:

Screenshot-2024-06-11-150857

prototype


Code Implementation of Image Segmentation Using Mean Shift Clustering in Python

Here, is the step by step code implementation of image Segmentation Using Mean Shift Clustering in Python.

Step 1: Import Libraries

Import the necessary libraries for image processing and clustering.

Python
import cv2
import numpy as np
from sklearn.cluster import MeanShift, estimate_bandwidth
from google.colab.patches import cv2_imshow

Step 2: Load the Image

Load the image from the specified path and check if it’s loaded successfully.

Python
# Load the image
image_path = '/content/Screenshot-2024-06-11-150857.webp'
image = cv2.imread(image_path)

# Check if the image was loaded successfully
if image is None:
    print(f"Error: Unable to load image at {image_path}")
else:
    # Convert the image to RGB
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

Step 3: Convert Image to Lab* Color Space

Convert the image from RGB to Lab* color space for better clustering.

Python
    # Convert image to L*a*b* color space
    lab_image = cv2.cvtColor(image, cv2.COLOR_RGB2LAB)

Step 4: Flatten the Image

Flatten the image to create a 2D array where each row represents a pixel with its Lab* values.

Python
    # Flatten the image
    flat_image = lab_image.reshape((-1, 3))

Step 5: Create Feature Space

Create a feature space that includes the Lab* values and the (x, y) coordinates of each pixel.

Python
    # Create the feature space [L, a, b, x, y]
    height, width, _ = image.shape
    x, y = np.meshgrid(np.arange(width), np.arange(height))
    flat_image_with_coordinates = np.column_stack([flat_image, x.flatten(), y.flatten()])

Step 6: Estimate Bandwidth for Mean Shift

Estimate the bandwidth parameter for the Mean Shift algorithm

Python
    # Estimate bandwidth for Mean Shift
    bandwidth = estimate_bandwidth(flat_image_with_coordinates, quantile=0.2, n_samples=500)

Step 7: Perform Mean Shift Clustering

Apply the Mean Shift clustering algorithm to the feature space.

Python
    # Perform Mean Shift clustering
    mean_shift = MeanShift(bandwidth=bandwidth, bin_seeding=True)
    mean_shift.fit(flat_image_with_coordinates)
    labels = mean_shift.labels_

Step 8: Reshape Labels to Image Shape

Reshape the cluster labels to match the original image dimensions.

Python
    # Reshape the labels to the original image shape
    segmented_image = labels.reshape((height, width))

Step 9: Generate Colored Segmented Image

Create a colored segmented image using random colors for each cluster.

Python
    # Generate a colored segmented image
    unique_labels = np.unique(labels)
    segmented_colors = np.random.randint(0, 255, size=(len(unique_labels), 3))
    colored_segmented_image = segmented_colors[segmented_image]

Step 10: Display the Original and Segmented Images

Display the original and the colored segmented images.

Python
    # Display the result using cv2_imshow
    cv2_imshow(image)
    cv2_imshow(colored_segmented_image)

Output:



In this image, the mean shift segmentation algorithm appears to have identified two main clusters, likely corresponding to the green and orange areas of the background. The brush stroke may not be well-defined because mean shift segmentation is not ideal for elongated or irregular shapes.

Conclusion

Mean shift is very good at detecting closely packed regions in the feature space, thus effectively segmenting the image based on color and spatial information. However, it is non-parametric and does not allow for the specification of a fixed number of clusters. Consequently it is useful for various kinds of images. It is successful in segmenting out coherent regions that are noise-resistant. While it handles noise well and produces coherent regions, it can be computationally intensive, particularly for high-resolution images. Despite this, its ability to generate accurate and intuitive segments makes it a valuable method in image processing and computer vision.

Image Segmentation Using Mean Shift Clustering FAQs:

What is Mean Shift clustering?

Mean Shift clustering is a non-parametric technique used for clustering data points, particularly in image segmentation. It involves iteratively shifting a window over the data to locate areas of high density, thus identifying clusters.

How does Mean Shift clustering work in image segmentation?

In image segmentation, Mean Shift clustering analyzes both color and spatial information to group pixels with similar characteristics into segments. It iteratively shifts a window over the image, converging towards modes (dense regions) in the feature space, resulting in segmented regions.

What are the advantages of Mean Shift clustering for image segmentation?

Mean Shift clustering is advantageous for image segmentation because it does not require specifying the number of clusters in advance, handles noise effectively, and produces coherent and contiguous segments. It also incorporates both color and spatial information, leading to meaningful segmentation results.

What are the main applications of image segmentation using Mean Shift clustering?

Image segmentation using Mean Shift clustering finds applications in various fields such as medical image analysis, object tracking, scene understanding, and image-based pattern recognition. It is particularly useful in tasks requiring region-based analysis and segmentation.

How does Mean Shift clustering compare to other segmentation methods like K-means?

Mean Shift clustering differs from K-means in that it is non-parametric and does not require specifying the number of clusters. It also works well with irregularly shaped clusters and can handle noise effectively. However, it can be computationally intensive compared to K-means.



Similar Reads

Mean Shift Clustering using Sklearn
Clustering is a fundamental method in unsupervised device learning, and one powerful set of rules for this venture is Mean Shift clustering. Mean Shift is a technique for grouping comparable data factors into clusters primarily based on their inherent characteristics, with our previous understanding of the number of clusters. This article explores
9 min read
Image Segmentation using K Means Clustering
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 t
4 min read
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
ML | Mean-Shift Clustering
Meanshift is falling under the category of a clustering algorithm in contrast of Unsupervised learning that assigns the data points to the clusters iteratively by shifting points towards the mode (mode is the highest density of data points in the region, in the context of the Meanshift). As such, it is also known as the Mode-seeking algorithm. Mean
6 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
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 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 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
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
three90RightbarBannerImg