使用 K 均值进行颜色量化#
对颐和园(中国)的图像执行像素级矢量量化 (VQ),将显示图像所需的顏色数量从 96,615 种独特顏色减少到 64 种,同时保留整体外观质量。
在本例中,像素在 3D 空间中表示,并使用 K 均值找到 64 个颜色簇。在图像处理文献中,从 K 均值获得的码本(聚类中心)称为颜色调色板。使用单个字节,最多可以寻址 256 种颜色,而 RGB 编码每个像素需要 3 个字节。例如,GIF 文件格式就使用这样的调色板。
为了进行比较,还显示了使用随机码本(随机选取颜色)的量化图像。
Fitting model on a small sub-sample of the data
done in 0.028s.
Predicting color indices on the full image (k-means)
done in 0.031s.
Predicting color indices on the full image (random)
done in 0.100s.
# Authors: Robert Layton <[email protected]>
# Olivier Grisel <[email protected]>
# Mathieu Blondel <[email protected]>
#
# License: BSD 3 clause
from time import time
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import load_sample_image
from sklearn.metrics import pairwise_distances_argmin
from sklearn.utils import shuffle
n_colors = 64
# Load the Summer Palace photo
china = load_sample_image("china.jpg")
# Convert to floats instead of the default 8 bits integer coding. Dividing by
# 255 is important so that plt.imshow works well on float data (need to
# be in the range [0-1])
china = np.array(china, dtype=np.float64) / 255
# Load Image and transform to a 2D numpy array.
w, h, d = original_shape = tuple(china.shape)
assert d == 3
image_array = np.reshape(china, (w * h, d))
print("Fitting model on a small sub-sample of the data")
t0 = time()
image_array_sample = shuffle(image_array, random_state=0, n_samples=1_000)
kmeans = KMeans(n_clusters=n_colors, random_state=0).fit(image_array_sample)
print(f"done in {time() - t0:0.3f}s.")
# Get labels for all points
print("Predicting color indices on the full image (k-means)")
t0 = time()
labels = kmeans.predict(image_array)
print(f"done in {time() - t0:0.3f}s.")
codebook_random = shuffle(image_array, random_state=0, n_samples=n_colors)
print("Predicting color indices on the full image (random)")
t0 = time()
labels_random = pairwise_distances_argmin(codebook_random, image_array, axis=0)
print(f"done in {time() - t0:0.3f}s.")
def recreate_image(codebook, labels, w, h):
"""Recreate the (compressed) image from the code book & labels"""
return codebook[labels].reshape(w, h, -1)
# Display all results, alongside original image
plt.figure(1)
plt.clf()
plt.axis("off")
plt.title("Original image (96,615 colors)")
plt.imshow(china)
plt.figure(2)
plt.clf()
plt.axis("off")
plt.title(f"Quantized image ({n_colors} colors, K-Means)")
plt.imshow(recreate_image(kmeans.cluster_centers_, labels, w, h))
plt.figure(3)
plt.clf()
plt.axis("off")
plt.title(f"Quantized image ({n_colors} colors, Random)")
plt.imshow(recreate_image(codebook_random, labels_random, w, h))
plt.show()
脚本总运行时间:(0 分钟 0.595 秒)
相关示例
矢量量化示例
手写数字数据上 K 均值聚类的演示
将希腊硬币的图片分割成区域
使用字典学习进行图像去噪