Skip to content

Instantly share code, notes, and snippets.

@StrikingLoo
Created June 2, 2019 18:26
Show Gist options
  • Save StrikingLoo/01f2c32ccf169137e4a0c80587ac5021 to your computer and use it in GitHub Desktop.
Save StrikingLoo/01f2c32ccf169137e4a0c80587ac5021 to your computer and use it in GitHub Desktop.
from dask_ml.cluster import KMeans
from PIL import Image
import numpy as np
#given the fitted k-means model and a vector of pixels, returns the new value for each pixel.
def clustered_pixels(x_fit, pixels):
labels = x_fit.predict(pixels).compute()
res= x_fit.cluster_centers_[labels]
return res
#defined in the previous gist.
np_im = pixels_from_path(file_path)
pixels = vector_of_pixels(np_im)
km = KMeans(n_clusters=k) # k = how many colors we want the new image to have
x_fit = km.fit(pixels) #we fit the centroids and labels.
clust_pixels = clustered_pixels(x_fit, pixels)
pic = reshape_pixels(clust_pixels, width, height) #turn vector to matrix again.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment