python - 图像压缩后得到的灰度图像

标签 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)
        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 的 broadcasting 高效地将标签转换为彩色图像。就像这样簇[标签]

演示

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

image = io.imread('/image/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

关于python - 图像压缩后得到的灰度图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52631869/

相关文章:

python - 解析\xd0\xb2\xd0\xbe 等时出现问题

python - 使用 virtualenv 和特定 Python 版本有困难吗?

java - 簇的质心 - KMedoids

python - 在没有临时文件的情况下将 JPEG 从 URL 加载到 skimage

python - 为物体检测选择/归一化 HoG 参数?

python - Python-版本列表而不是不可变列表?

python - 云函数将 CSV 发送到云存储

python - 在 KMeans 聚类(scikit 学习)之后查找聚类的长度(与聚类相关联的点数)

java - K-Means迭代处理输出/群集2失败

python - 从二值化图像中删除特征