K-Means Clustering for the image with Scikit-image — MRI Scan| Python Part 1
2 min readJun 16, 2020
Hello! Welcome Back.
Jupyter Notebook
Image: https://live.staticflickr.com/2456/3854685038_48bc4c8b02_z.jpg
Dependencies
import matplotlib.pyplot as plt
from skimage.color import rgb2gray
import skimage.io
import numpy as np
RGB to rgb2gray
data=skimage.io.imread("MRI_blackandwhite.png")
#split original and grayscale
original = data
grayscale = rgb2gray(original)fig, axes = plt.subplots(1, 2, figsize=(8, 4))
ax = axes.ravel()ax[0].imshow(original)
ax[0].set_title("Original")
ax[1].imshow(grayscale, cmap=plt.cm.gray)
ax[1].set_title("Grayscale")fig.tight_layout()
plt.show()
output:
Reshape 2D
image_gray= grayscale.reshape(grayscale.shape[0] * grayscale.shape[1], 1)
Shape:
image_gray.shape
output:
(238550, 1)
Model: Kmeans, n_cluster=6;
from sklearn.cluster import KMeans
n=6
kmeans = KMeans(n_clusters=n, random_state=0).fit(image_gray)
clustered = kmeans.cluster_centers_[kmeans.labels_]
Image Cluster
output:
code in python:
To be continued…
Github:
So, Keep Learning. God Bless You.👍😉