.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/image-radar/plot_hs_clustering.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_image-radar_plot_hs_clustering.py: ==================================================================== Segmentation of hyperspectral image with Riemannian geometry ==================================================================== This example compares clustering pipelines based on covariance matrices for hyperspectral image segmentation [1]_. .. GENERATED FROM PYTHON SOURCE LINES 9-21 .. code-block:: Python # Author: Ammar Mian import matplotlib.pyplot as plt import numpy as np from sklearn.pipeline import Pipeline from pyriemann.clustering import Kmeans from pyriemann.estimation import Covariances from helpers.datasets_helpers import download_salinas, read_salinas from helpers.processing_helpers import PCAImage, SlidingWindowVectorize .. GENERATED FROM PYTHON SOURCE LINES 22-24 Parameters ---------- .. GENERATED FROM PYTHON SOURCE LINES 24-33 .. code-block:: Python window_size = 5 data_path = "./data" n_jobs = -1 max_iter = 100 small_dataset = True # Whole image can take time n_components = 5 # For PCA dimensionality reduction estimator = "scm" # Chose any estimator from "scm", "lwf", "oas", "mcd", "hub" .. GENERATED FROM PYTHON SOURCE LINES 34-36 Load data --------- .. GENERATED FROM PYTHON SOURCE LINES 36-63 .. code-block:: Python print("Loading Salinas data") download_salinas(data_path) data, labels, labels_names = read_salinas(data_path) data_visualization = data.copy() # To avoid aliasing when showing data n_clusters = len(labels_names) resolution = 3.7 # m, obtained from documentation of Salinas dataset # For visualization of image x_values = np.arange(0, data.shape[1]) * resolution y_values = np.arange(0, data.shape[0]) * resolution X_image, Y_image = np.meshgrid(x_values, y_values) if small_dataset: reduce_factor = 5 data = data[::reduce_factor, ::reduce_factor] max_iter = 5 resolution = reduce_factor*resolution height, width, n_features = data.shape # For visualization of results x_values = np.arange(window_size//2, width-window_size//2) * resolution y_values = np.arange(window_size//2, height-window_size//2) * resolution X_res, Y_res = np.meshgrid(x_values, y_values) .. rst-class:: sphx-glr-script-out .. code-block:: none Loading Salinas data .. GENERATED FROM PYTHON SOURCE LINES 64-66 Print configuration ------------------- .. GENERATED FROM PYTHON SOURCE LINES 66-75 .. code-block:: Python print(f"Size of dataset: {data.shape}") print(f"n_clusters = {n_clusters}") print(f"window_size = {window_size}") print(f"n_components = {n_components}") print(f"n_jobs = {n_jobs}") print(f"max_iter = {max_iter}") print(f"estimator = {estimator}") .. rst-class:: sphx-glr-script-out .. code-block:: none Size of dataset: (103, 44, 204) n_clusters = 17 window_size = 5 n_components = 5 n_jobs = -1 max_iter = 5 estimator = scm .. GENERATED FROM PYTHON SOURCE LINES 76-78 Pipelines definition -------------------- .. GENERATED FROM PYTHON SOURCE LINES 78-109 .. code-block:: Python pipeline_euclid = Pipeline([ ("pca", PCAImage(n_components=n_components)), ("sliding_window", SlidingWindowVectorize(window_size=window_size)), ("covariances", Covariances(estimator=estimator)), ("kmeans", Kmeans( n_clusters=n_clusters, n_jobs=n_jobs, max_iter=max_iter, metric="euclid", )) ], verbose=True) pipeline_riemann = Pipeline([ ("pca", PCAImage(n_components=n_components)), ("sliding_window", SlidingWindowVectorize(window_size=window_size)), ("covariances", Covariances(estimator=estimator)), ("kmeans", Kmeans( n_clusters=n_clusters, n_jobs=n_jobs, max_iter=max_iter, metric="riemann", )) ], verbose=True) pipelines = [pipeline_euclid, pipeline_riemann] pipelines_names = [ f"{estimator} Euclidean distance", f"{estimator} Riemannian distance", ] .. GENERATED FROM PYTHON SOURCE LINES 110-112 Perform clustering ------------------ .. GENERATED FROM PYTHON SOURCE LINES 112-124 .. code-block:: Python print(f"\nStarting clustering with pipelines: {pipelines_names}") results = {} for pipeline_name, pipeline in zip(pipelines_names, pipelines): print("-"*60) print(f"Pipeline: {pipeline_name}") pipeline.fit(data) preds = pipeline.named_steps["kmeans"].labels_ results[pipeline_name] = \ pipeline.named_steps["sliding_window"].inverse_predict(preds) print("-"*60) .. rst-class:: sphx-glr-script-out .. code-block:: none Starting clustering with pipelines: ['scm Euclidean distance', 'scm Riemannian distance'] ------------------------------------------------------------ Pipeline: scm Euclidean distance [Pipeline] ............... (step 1 of 4) Processing pca, total= 0.0s [Pipeline] .... (step 2 of 4) Processing sliding_window, total= 0.0s [Pipeline] ....... (step 3 of 4) Processing covariances, total= 0.1s [Pipeline] ............ (step 4 of 4) Processing kmeans, total= 10.9s ------------------------------------------------------------ ------------------------------------------------------------ Pipeline: scm Riemannian distance [Pipeline] ............... (step 1 of 4) Processing pca, total= 0.0s [Pipeline] .... (step 2 of 4) Processing sliding_window, total= 0.0s [Pipeline] ....... (step 3 of 4) Processing covariances, total= 0.1s [Pipeline] ............ (step 4 of 4) Processing kmeans, total= 46.4s ------------------------------------------------------------ .. GENERATED FROM PYTHON SOURCE LINES 125-127 Plot data --------- .. GENERATED FROM PYTHON SOURCE LINES 127-138 .. code-block:: Python plot_value = np.mean(data_visualization, axis=2) figure, ax = plt.subplots(figsize=(7, 5)) plt.pcolormesh(X_image, Y_image, plot_value, cmap="gray") plt.colorbar() ax.invert_yaxis() plt.xlabel("x (m)") plt.ylabel("y (m)") plt.title("Salinas dataset (mean over bands)") plt.tight_layout() .. image-sg:: /auto_examples/image-radar/images/sphx_glr_plot_hs_clustering_001.png :alt: Salinas dataset (mean over bands) :srcset: /auto_examples/image-radar/images/sphx_glr_plot_hs_clustering_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 139-141 Plot results ------------ .. GENERATED FROM PYTHON SOURCE LINES 141-155 .. code-block:: Python for pipeline_name, labels_pred in results.items(): figure, ax = plt.subplots(figsize=(7, 5)) plt.pcolormesh(X_res, Y_res, labels_pred, cmap="tab20b") plt.xlim(X_image.min(), X_image.max()) plt.ylim(Y_image.min(), Y_image.max()) plt.title(f"Clustering with {pipeline_name}") plt.colorbar() ax.invert_yaxis() plt.xlabel("x (m)") plt.ylabel("y (m)") plt.tight_layout() plt.show() .. rst-class:: sphx-glr-horizontal * .. image-sg:: /auto_examples/image-radar/images/sphx_glr_plot_hs_clustering_002.png :alt: Clustering with scm Euclidean distance :srcset: /auto_examples/image-radar/images/sphx_glr_plot_hs_clustering_002.png :class: sphx-glr-multi-img * .. image-sg:: /auto_examples/image-radar/images/sphx_glr_plot_hs_clustering_003.png :alt: Clustering with scm Riemannian distance :srcset: /auto_examples/image-radar/images/sphx_glr_plot_hs_clustering_003.png :class: sphx-glr-multi-img .. GENERATED FROM PYTHON SOURCE LINES 156-162 References ---------- .. [1] "Hyperspectral Image Clustering: Current achievements and future lines" H. Zhai, H. Zhang, P. Li and L. Zhang. IEEE Geoscience and Remote Sensing Magazine, pp. 35-67. 2021 .. rst-class:: sphx-glr-timing **Total running time of the script:** (2 minutes 29.440 seconds) .. _sphx_glr_download_auto_examples_image-radar_plot_hs_clustering.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_hs_clustering.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_hs_clustering.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_hs_clustering.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_