Python 图像压缩后得到的灰度图像

Python 图像压缩后得到的灰度图像,python,k-means,scikit-image,image-compression,lossy-compression,Python,K Means,Scikit Image,Image Compression,Lossy Compression,我正在使用K均值聚类算法进行图像压缩。压缩后获得的图像是灰度图像,如何获得与原始图像质量相似的彩色图像 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)

我正在使用K均值聚类算法进行图像压缩。压缩后获得的图像是灰度图像,如何获得与原始图像质量相似的彩色图像

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);

您可以通过Numpy这样的
群集[标签]
标签有效地转换为彩色图像

演示

输入图像的质量会自动降低,压缩图像的质量也不好。但是,我得到了彩色图像。我怎样才能提高质量?你能试着让图像有一些文字吗?我建议你使用
n_clusters
的值。如果使用128个以上的簇,则量化彩色图像的质量应得到改善。
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)