Segmenting images with spectral clustering

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.

How to do it...

  1. 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
  2. Load the digits data set as follows:
    digits = load_digits()
    img = digits.images[0].astype(float)
    mask = img.astype(bool)
  3. Create a graph from the image:
    graph = img_to_graph(img, mask=mask)
    graph.data = np.exp(-graph.data/graph.data.std())
  4. Apply spectral clustering to get three clusters:
    labels = spectral_clustering(graph, n_clusters=3)
    label_im = -np.ones(mask.shape)
    label_im[mask] = labels
  5. Plot the original image as follows:
    plt.matshow(img, False)
    plt.gca().axis('off')
    plt.title('Original')
  6. Plot the image with the three clusters as follows:
    plt.figure()
    plt.matshow(label_im, False)
    plt.gca().axis('off')
    plt.title('Clustered')

Refer to the following screenshot for the end result:

How to do it...

The code is in the clustering_spectral.ipynb file in this book's code bundle.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset