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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-05-05 06:00:11 +0000
Seen: 8 times
Last updated: May 05 '23
What is the method to avoid mixing shades when using transparency?
What is the method for creating a barplot with different colors for each bar?
How can one modify certain colors within a color palette manually?
What is the process for adding several colors to the title of a tmux pane?
Can the choropleth map incorporate various shapes for depicting different colors on the map?
In ggplot, certain bin intervals in the legend are lacking color.