Spectral Spatial Kmeans

The spectral_spatial_kmeans() function performs a hybrid segmentation on a DataCube by first clustering spectral signatures with standard KMeans and then enforcing spatial coherence through Markov Random Field (MRF) regularization. Initially, each pixel’s spectrum is assigned to one of K clusters based solely on spectral distance. Subsequently, a smoothing step refines labels to encourage neighboring pixels to share the same cluster, reducing salt-and-pepper noise and emphasizing spatially contiguous regions.

Example

The following example demonstrates spectral–spatial KMeans on a synthetically generated DataCube.

 1import wizard
 2from wizard._utils.example import generate_pattern_stack
 3from wizard._processing.cluster import spectral_spatial_kmeans
 4import matplotlib.pyplot as plt
 5
 6# generate synthetic data with spatial patterns
 7data = generate_pattern_stack(12, 400, 400, n_circles=5, n_rects=3, n_triangles=1)
 8
 9# create a DataCube
10dc = wizard.DataCube(data)
11
12# apply spectral–spatial KMeans clustering
13labels = spectral_spatial_kmeans(dc, n_clusters=4, spatial_radius=2)
14
15# visualize a wavelength slice and the segmentation
16fig, axes = plt.subplots(1, 2, figsize=(10, 5))
17
18axes[0].imshow(dc[7])
19axes[0].set_title("Original Slice (λ index 7)")
20axes[0].set_axis_off()
21
22axes[1].imshow(labels)
23axes[1].set_title("Segmented (Spectral–Spatial KMeans)")
24axes[1].set_axis_off()
25
26plt.tight_layout()
27plt.show()
Cluster DataCube with smooth_kmeans().

The result highlights how pure spectral clustering followed by spatial smoothing yields segments that honor both spectral similarity and contiguous spatial patterns.