Image Segmentation in Python- Practical Hands-On (3)
Image Segmentation in Python- Practical Hands-On (3)
Principle:
This method detects object boundaries by identifying regions with sudden
changes in pixel intensity (gradients).
It relies on the assumption that object edges are characterized by high
contrast compared to the background.
Steps:
Compute the gradient of the image intensity using edge detectors
(e.g., Sobel, Prewitt, or Laplacian operators).
Threshold the gradient values to retain the strongest edges.
Use edge linking to form continuous boundaries.
Edge-based Method
Common Techniques:
Sobel Operator: Calculates the gradient in the horizontal and vertical directions.
Canny Edge Detector: Combines Gaussian smoothing, gradient calculation, non-
maximum suppression, and double-thresholding for robust edge detection.
Applications:
Object boundary detection.
Feature extraction for object recognition.
Road and building detection in satellite imagery.
Challenges:
Sensitive to noise (may require preprocessing like Gaussian smoothing).
May fail to close gaps in edges, leading to incomplete segmentation.
Does not provide region information, only boundaries.
Edge-Based Method- Code Example
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Plot results
plt.figure(figsize=(10, 5))
plt.subplot(1, 3, 1), plt.title("Original Image"), plt.imshow(image, cmap='gray')
plt.subplot(1, 3, 2), plt.title("Sobel Edges"), plt.imshow(np.abs(edges_sobel),
cmap='gray')
plt.subplot(1, 3, 3), plt.title("Canny Edges"), plt.imshow(edges_canny, cmap='gray')
plt.show()
Clustering-Based Method
Principle:
Groups pixels with similar features (e.g., intensity, color, or texture)
into clusters.
It uses statistical or machine learning algorithms to partition the
image into distinct segments.
Steps:
Extract features from each pixel (e.g., RGB values, spatial location).
Apply clustering algorithms (e.g., K-means, Mean-shift, Gaussian
Mixture Models).
Assign each pixel to a cluster, effectively segmenting the image.
Clustering-Based Method
Common Techniques:
K-means Clustering:
Partitions pixels into k clusters by minimizing the variance within
each cluster.
Mean-Shift Clustering:
Identifies high-density regions in feature space to form clusters.
Gaussian Mixture Model (GMM):
Uses probabilistic modeling for clustering.
Clustering-Based Method
Applications:
Color segmentation (e.g., separating different parts of an image based on
color).
Texture segmentation in remote sensing or biological imaging.
Object segmentation in computer vision tasks.
Challenges:
Requires prior knowledge of the number of clusters (k) in methods like K-
means.
Sensitive to initialization (e.g., cluster centroids in K-means).
May struggle with overlapping regions or noise.
K-means clustering
Step 4: Re-assignment
Using the new centroids, assign points again:
New Calculations:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
# Dataset
X = np.array([[2, 3], [3, 3], [6, 8], [7, 9], [1, 0], [2, 1]])
# KMeans Clustering
kmeans = KMeans(n_clusters=2, random_state=42)
kmeans.fit(X)
# Results
labels = kmeans.labels_
centroids = kmeans.cluster_centers_
K-means clustering – Simple Example
# Visualization
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis', marker='o',
label='Data Points')
plt.scatter(centroids[:, 0], centroids[:, 1], c='red', marker='x',
s=200, label='Centroids')
plt.title('K-Means Clustering')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()
plt.grid()
plt.show()
K-means Clustering for Image
Segmentation – Code Example
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
# Step 2: Reshape the image into a 2D array of pixels and 3 color values
(R, G, B)
pixel_values = image.reshape((-1, 3))
pixel_values = np.float32(pixel_values)
K-means Clustering for Image
Segmentation – Code Example
# Step 3: Define the number of clusters (k)
k = 3 # You can experiment with different values of k
segmented_image = centers[labels.flatten()]
segmented_image = segmented_image.reshape(image.shape)
K-means Clustering for Image
Segmentation – Code Example
# Step 6: Visualize the original and segmented image
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title("Original Image")
plt.imshow(image)
plt.axis("off")
plt.subplot(1, 2, 2)
plt.title(f"Segmented Image (k={k})")
plt.imshow(segmented_image)
plt.axis("off")
plt.tight_layout()
plt.show()
K-means Clustering for Image Segmentation– Code Example
for i in range(k):
# Create a mask for the current cluster
cluster_mask = labels.reshape(image.shape[:2]) == i
plt.tight_layout()
plt.show()
Summary
Comparison Between Edge-Based and Clustering-Based Methods