<jupyter_start><jupyter_text>Images can be compressed in a different way. Each image can be stored as a 3 dimensional matrix where each pixel is represented by a 3-dimensional vector.By clustering these pixel vectors into $k$ clusters, each pixel can be assigned to the closest cluster centroid. In this way, each pixel is replaced by one of the $k$ cluster centroids, so the original image can be represented with only $k$ three-dimensional vector.<jupyter_code>from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

from sklearn.cluster import KMeans
image = np.array(Image.open("images/Castle_hill.jpg"))
image = image / 255
row, col, _ = image.shape
print("pixels in one channel: {} * {}".format(row, col))
fig = plt.figure(figsize=(15, 10))
img = fig.add_subplot(1, 1, 1)
imgplot = plt.imshow(image)
img.set_title("Castle hill, Budapest")
plt.show()
X = image.reshape(row * col, 3)
kmeans = KMeans(n_clusters=4, n_init=8, max_iter=30).fit(X)
cluster_centers = kmeans.cluster_centers_
indices = kmeans.predict(X)<jupyter_output><empty_output><jupyter_text>To store the compressed image we only need the cluster centroids and an integer vector that assigns the closest cluster centroid to each pixel.<jupyter_code>X_compressed = cluster_centers[indices, :].reshape(row, col, 3)
X_compressed.shape
fig = plt.figure(figsize=(15, 10))
img = fig.add_subplot(1, 1, 1)
imgplot = plt.imshow(X_compressed)
img.set_title("Castle hill, Budapest")
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10124101894186806, 'fraction_numerical': 0.016329196603527107, 'mean_word_length': 5.932126696832579, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '559113', 'license': 'MIT', 'n_tokens_mistral': 519, 'n_tokens_neox': 496, 'n_words': 169, 'path': 'image_compression/image_compression_with_clustering.ipynb', 'repo_name': 'ghostrider77/data_science_workshop', 'size': '1531'}