DOC Fix notebook style of plot_coin_ward_segmentation
@@ -13,40 +13,51 @@ for each segmented region to be in one piece.
# Alexandre Gramfort, 2011
# License: BSD 3 clause
-import time as time
-
-import numpy as np
-from scipy.ndimage import gaussian_filter
-
-import matplotlib.pyplot as plt
+# %%
+# Generate data
+# -------------
from skimage.data import coins
-from skimage.transform import rescale
-from sklearn.feature_extraction.image import grid_to_graph
-from sklearn.cluster import AgglomerativeClustering
-
-
-# #############################################################################
-# Generate data
orig_coins = coins()
+# %%
# Resize it to 20% of the original size to speed up the processing
# Applying a Gaussian filter for smoothing prior to down-scaling
# reduces aliasing artifacts.
+
+import numpy as np
+from scipy.ndimage import gaussian_filter
+from skimage.transform import rescale
+
smoothened_coins = gaussian_filter(orig_coins, sigma=2)
rescaled_coins = rescale(
- smoothened_coins, 0.2, mode="reflect", anti_aliasing=False, multichannel=False
+ smoothened_coins,
+ 0.2,
+ mode="reflect",
+ anti_aliasing=False,
)
X = np.reshape(rescaled_coins, (-1, 1))
-# #############################################################################
-# Define the structure A of the data. Pixels connected to their neighbors.
+# %%
+# Define structure of the data
+# ----------------------------
+#
+# Pixels are connected to their neighbors.
+
+from sklearn.feature_extraction.image import grid_to_graph
+
connectivity = grid_to_graph(*rescaled_coins.shape)
-# #############################################################################
+# %%
# Compute clustering
+# ------------------
+
+import time as time
+
+from sklearn.cluster import AgglomerativeClustering
+
print("Compute structured hierarchical clustering...")
st = time.time()
n_clusters = 27 # number of regions
@@ -55,12 +66,20 @@ ward = AgglomerativeClustering(
)
ward.fit(X)
label = np.reshape(ward.labels_, rescaled_coins.shape)
-print("Elapsed time: ", time.time() - st)
-print("Number of pixels: ", label.size)
-print("Number of clusters: ", np.unique(label).size)
+print(f"Elapsed time: {time.time() - st:.3f}s")
+print(f"Number of pixels: {label.size}")
+print(f"Number of clusters: {np.unique(label).size}")
-# #############################################################################
+# %%
# Plot the results on an image
+# ----------------------------
+#
+# Agglomerative clustering is able to segment each coin however, we have had to
+# use a ``n_cluster`` larger than the number of coins because the segmentation
+# is finding a large in the background.
+
+import matplotlib.pyplot as plt
+
plt.figure(figsize=(5, 5))
plt.imshow(rescaled_coins, cmap=plt.cm.gray)
for l in range(n_clusters):
@@ -70,6 +89,5 @@ for l in range(n_clusters):
plt.cm.nipy_spectral(l / float(n_clusters)),
],
)
-plt.xticks(())
-plt.yticks(())
+plt.axis("off")
plt.show()
