Logo elodees  elodees

A caring AI for a better world













Only alphabetic characters accented or not as well as the space are accepted

Logo IA




Color quantization kmeans





No account yet ?

Sign up to access all content




Tested in Anaconda and Python 3.7

import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from skimage.io import imread, imsave
 
n_colors = 2
 
sample_img = imread('image.jpg')
 
w,h,_ = sample_img.shape
sample_img = sample_img.reshape(w*h,3)
kmeans = KMeans(n_clusters=n_colors, random_state=0).fit(sample_img)
# find out which cluster each pixel belongs to.
labels = kmeans.predict(sample_img)
# the cluster centroids is our color palette
identified_palette = np.array(kmeans.cluster_centers_).astype(int)
# recolor the entire image
recolored_img = np.copy(sample_img)
for index in range(len(recolored_img)):
    recolored_img[index] = identified_palette[labels[index]]
 
# reshape for display
recolored_img = recolored_img.reshape(w,h,3)
 
imsave('kmeans_color_q.jpg', recolored_img)
plt.imshow(recolored_img)
plt.axis('off')
plt.show()
 


ml_research - GitHub



Original image

Free image provided by pexel.com

Quantized image

Free image provided by pexel.com












Welcome, my name is Eric Soupet and I am the administrator of the site elodees.com. elodees.com is a state of the art of Artificial Intelligence and aims to be collaborative, you can now offer content such as articles, events, tutorials, ... so don't hesitate !

Platform images credit : Pixabay - Pixabay License | Pexels - Pexels License