We overviewed Classical Image Segmentation methods in my previous post. Now it is time to examine AI-based Image Segmentation methods and we will start with Clustering.
Before diving into Image Segmentation with Clustering, let’s go over the topics like “What is Clustering?” “How to implement a basic Clustering method with Python?”
What is Clustering
It is nothing more than grouping given data according to their similarities and obtains different clusters at the end. According to the clustering method we use, the way we group the data changes. Let’s examine 2 different most used in Image Segmentation type: Partitioning Clustering and Fuzzy Clustering
Partitioning Clustering methods subdivides the data into k groups, where k is a number predefined by the user. For K-means Clustering which is the most popular Partitioning Cluster method
- We choose k random points in the data as the center of clusters and assign each point to the nearest cluster by looking at the L2 distance between the point and the center.
- Compute the mean of each cluster, assign that mean value as the new center of the cluster.
- Reassign each data point to its closest cluster center. Repeat step 2.
The process keeps going until no new assignment is performed (so the model is converged, there is nothing to go furthermore) or for a given number of iteration. Therefore, K-means Clustering is an iterative method where we can determine the iteration number too.
Now let’s visualize some random data applying K-means clustering for 10 iterations for each.
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
import numpy as np
from matplotlib import pyplot as plt
import cv2""" Plot the data """data = np.array([[1, 2], [1, 4], [1, 0],[10, 2], [10, 4], [10, 0]])
data = np.array([[1, 5], [3, 1], [10, 3], [10, 2], [10, 1], [1, 0], [2, 15], [0.5, 4.9], [5, 3], [7, 13], [18, 18], [1.9, 0.5]])
data = np.random.randint(100, size=(2,2))centers = [[1, 1], [-1, -1], [1, -1]]
data, _ = make_blobs(n_samples=10000, centers=centers, cluster_std=0.6)# Plot the data
plt.show()""" Visualize K means for each iteration """""" create an empty list for each cluster, k is the cluster number """k = 2
clusters = [[[0 for _ in range(2)] for _ in range(1)] for _ in range(k)]for i in range(k):
clusters[i].pop() #if we dont do...
Continue reading: https://towardsdatascience.com/image-segmentation-with-clustering-b4bbc98f2ee6?source=rss—-7f60cf5620c9—4