1

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);
martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

2

You can efficiently convert labels into a color image through Numpy's broadcasting like this clusters[labels].

Demo

from skimage import io
from sklearn.cluster import MiniBatchKMeans
import numpy as np
import matplotlib.pyplot as plt

image = io.imread('https://i.stack.imgur.com/LkU1i.jpg')
rows = image.shape[0]
cols = image.shape[1]

pixels = image.reshape(image.shape[0] * image.shape[1], image.shape[2])
kmeans = MiniBatchKMeans(n_clusters=128, n_init=10, max_iter=200)
kmeans.fit(pixels)

clusters = np.asarray(kmeans.cluster_centers_, dtype=np.uint8)
labels = np.asarray(kmeans.labels_, dtype=np.uint8).reshape(rows, cols)

colored = clusters[labels]

d = {'Image': image, 'Labels': labels, 'Colored': colored}

fig, ax = plt.subplots(1, 3)

for i, name in enumerate(d):
    cmap = 'gray' if d[name].ndim == 2 else 'jet'
    ax[i].imshow(d[name], cmap=cmap)
    ax[i].axis('off')
    ax[i].set_title(name)

plt.show(fig)

Results

Community
  • 1
  • 1
Tonechas
  • 13,398
  • 16
  • 46
  • 80
  • The quality of the input image automatically degrades and the compressed image is also not good in quality. But, I got the coloured image. How can I improve the quality? Can you try with image having some text? – user9546843 Oct 04 '18 at 11:50
  • I would recommend you to play around with the value of `n_clusters`. If you use more than 128 clusters the quality of the quantized color image should be improved. – Tonechas Oct 04 '18 at 12:47