import math
import numpy as np
import matplotlib.pyplot as plt
from skimage import io, measure
from sklearn.cluster import KMeans
%matplotlib inline
image_ch_0 = io.imread("../images/002002-3608-channel-0.tif")
image_ch_1 = io.imread("../images/002002-3608-channel-1.tif")
image_ch_2 = io.imread("../images/002002-3608-channel-2.tif")
rows, cols = image_ch_0.shape
print(rows)
print(cols)
fig, ax = plt.subplots(figsize=(15, 15))
plt.subplot(1,3,1)
plt.imshow(image_ch_0, cmap='gray')
plt.subplot(1,3, 2)
plt.imshow(image_ch_1, cmap='gray')
plt.subplot(1,3, 3)
plt.imshow(image_ch_2, cmap='gray')
plt.show()
Construct the data matrix
ch_0 = image_ch_0.flatten()
ch_1 = image_ch_1.flatten()
ch_2 = image_ch_2.flatten()
data = np.array([ch_0, ch_1, ch_2])
data = np.transpose(data)
print(data.shape)
Here you would need to define the number of clusters as well as the initialisation method. Refer to the documentation to learn more about the parameter settings.
estimator = KMeans(n_clusters=6, n_init=1, init='random')
estimator.fit(data)
labels = estimator.labels_
print(labels.shape)
label_image = np.reshape(labels, (rows, cols))
fig, ax = plt.subplots(figsize=(10, 10))
plt.subplot(1,2,1)
plt.imshow(image_ch_0, cmap='gray')
plt.subplot(1,2, 2)
plt.imshow(label_image)
plt.show()
labels, N = measure.label(label_image, return_num=True)
fig, ax = plt.subplots(figsize=(10, 10))
plt.imshow(labels)