Ask Your Question
0

How can PIL and numpy be employed to quantize an image?

asked 2023-05-05 06:00:11 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-05-05 06:13:02 +0000

woof gravatar image

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:

  1. Read the image using PIL's Image module
from PIL import Image
img = Image.open("image.jpg")
  1. Convert the image to a numpy array
import numpy as np
img_arr = np.array(img)
  1. Flatten the numpy array to a 2-dimensional array (pixels x 3 RGB channels)
img_arr_flat = img_arr.reshape(-1, 3)
  1. Perform k-means clustering on the flattened array, where k is the desired number of colors
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=16) # 16 colors
kmeans.fit(img_arr_flat)
  1. Get the centroid values of the clusters
centroid_vals = kmeans.cluster_centers_.astype(int)
  1. Replace the pixel values in the original numpy array with the nearest centroid pixel value
centroid_idx = kmeans.predict(img_arr_flat)
quantized_arr_flat = centroid_vals[centroid_idx]
quantized_arr = quantized_arr_flat.reshape(img_arr.shape)
  1. Convert the quantized numpy array back to a PIL Image object
quantized_img = Image.fromarray(np.uint8(quantized_arr))
  1. Save the quantized image
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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-05-05 06:00:11 +0000

Seen: 8 times

Last updated: May 05 '23