Skip to content

Instantly share code, notes, and snippets.

@lxpnh98
Created October 26, 2019 01:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lxpnh98/50aceafc7675b80c05359426d05cbc94 to your computer and use it in GitHub Desktop.
Save lxpnh98/50aceafc7675b80c05359426d05cbc94 to your computer and use it in GitHub Desktop.
# script to get palette of an image (5 main colors)
import sys
from skimage.io import imread, imshow
from skimage.color import rgb2hsv
from sklearn.cluster import KMeans
# [a] -> [(a, a, a)]
def group(lst, n):
for i in range(0, len(lst), n):
val = lst[i:i+n]
if len(val) == n:
yield tuple(val)
# read image from first argument and convert to HSV
img = rgb2hsv(imread(sys.argv[1]))
# get list of colors
colors = list(group(img.flatten(), 3))
# perform KMeans fit
kmeans = KMeans(n_clusters=5).fit(colors)
# cluster centers represent the palette
print(kmeans.cluster_centers_)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment