Hướng dẫn color quantization python - trăn lượng tử hóa màu

Ghi chú

Nhấn vào đây để tải xuống mã ví dụ đầy đủ hoặc để chạy ví dụ này trong trình duyệt của bạn thông qua Binderhere to download the full example code or to run this example in your browser via Binder

Thực hiện một lượng tử hóa vector khôn ngoan (VQ) của hình ảnh của Cung điện mùa hè (Trung Quốc), giảm số lượng màu cần thiết để hiển thị hình ảnh từ 96.615 màu độc đáo xuống còn 64, trong khi bảo tồn chất lượng ngoại hình tổng thể.

Trong ví dụ này, các pixel được biểu diễn trong không gian 3D và K-means được sử dụng để tìm 64 cụm màu.Trong tài liệu xử lý hình ảnh, cuốn sách mã thu được từ K-MEAN (trung tâm cụm) được gọi là bảng màu.Sử dụng một byte duy nhất, có thể giải quyết tối đa 256 màu, trong khi mã hóa RGB yêu cầu 3 byte mỗi pixel.Ví dụ, định dạng tệp GIF sử dụng bảng màu như vậy.

Để so sánh, một hình ảnh được định lượng sử dụng một cuốn sách mã ngẫu nhiên (màu sắc được chọn ngẫu nhiên) cũng được hiển thị.

Fitting model on a small sub-sample of the data
done in 0.113s.
Predicting color indices on the full image (k-means)
done in 0.041s.
Predicting color indices on the full image (random)
done in 0.064s.

# Authors: Robert Layton <>
#          Olivier Grisel <>
#          Mathieu Blondel <>
#
# License: BSD 3 clause

import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import pairwise_distances_argmin
from sklearn.datasets import load_sample_image
from sklearn.utils import shuffle
from time import time

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 behaves 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()

Tổng thời gian chạy của tập lệnh: (0 phút 0,551 giây) ( 0 minutes 0.551 seconds)

Phòng trưng bày được tạo ra bởi Sphinx-Gallery