Quantization is the process of reducing the number of distinct colors in an image. Here's how you can use PIL and numpy to quantize an image:
from PIL import Image
img = Image.open("image.jpg")
import numpy as np
img_arr = np.array(img)
img_arr_flat = img_arr.reshape(-1, 3)
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=16) # 16 colors
kmeans.fit(img_arr_flat)
centroid_vals = kmeans.cluster_centers_.astype(int)
centroid_idx = kmeans.predict(img_arr_flat)
quantized_arr_flat = centroid_vals[centroid_idx]
quantized_arr = quantized_arr_flat.reshape(img_arr.shape)
quantized_img = Image.fromarray(np.uint8(quantized_arr))
quantized_img.save("quantized_image.jpg")
This will produce an image with the same dimensions as the original, but with a reduced color palette of 16 colors. You can adjust the number of colors by changing the n_clusters
parameter in step 4.
Asked: 2023-05-05 06:00:11 +0000
Seen: 11 times
Last updated: May 05 '23