Spectral clustering is a clustering technique that can be used to segment images. The scikit-learn spectral_clustering()
function implements the normalized graph cuts spectral clustering algorithm. This algorithm represents an image as a graph of units. "Graph" here is the same mathematical concept as in Chapter 8, Text Mining and Social Network Analysis. The algorithm tries to partition the image, while minimizing segment size and the ratio of intensity gradient along cuts.
The imports are as follows:
import numpy as np import matplotlib.pyplot as plt from sklearn.feature_extraction.image import img_to_graph from sklearn.cluster import spectral_clustering from sklearn.datasets import load_digits
Load the digits data set as follows:
digits = load_digits() img = digits.images[0].astype(float) mask = img.astype(bool)
Create a graph from the image:
graph = img_to_graph(img, mask=mask) graph.data = np.exp(-graph.data/graph.data.std())
Apply...