I am performing image compression using K means clustering algorithm. The images obtained after compression are grayscale, how can I obtain colored image with similar quality as original?
import os
from skimage import io
from sklearn.cluster import MiniBatchKMeans
import numpy as np
algorithm = "full"
for f in os.listdir('.'):
if f.endswith('.png'):
image = io.imread(f)
rows = image.shape[0]
cols = image.shape[1]
image = image.reshape(image.shape[0] * image.shape[1], image.shape[2])
kmeans = MiniBatchKMeans(n_clusters=128, n_init=10, max_iter=200)
kmeans.fit(image)
clusters = np.asarray(kmeans.cluster_centers_, dtype=np.uint8)
labels = np.asarray(kmeans.labels_, dtype=np.uint8)
labels = labels.reshape(rows, cols);
# np.save('codebook'+f+'.npy', clusters)
io.imsave('compressed_' + f , labels);
You can efficiently convert
labels
into a color image through Numpy's broadcasting like thisclusters[labels]
.Demo