Skip to content

Instantly share code, notes, and snippets.

@twiddles
Created May 25, 2017 18:40
Show Gist options
  • Save twiddles/5dbc0cba68373ca792c9d32b433e6dab to your computer and use it in GitHub Desktop.
Save twiddles/5dbc0cba68373ca792c9d32b433e6dab to your computer and use it in GitHub Desktop.
import matplotlib.pyplot as plt
def dominant_colors(img):
img = cv2.resize(img, (64, 64))
all_colors = img.reshape(-1, 3)
kmeans = KMeans(n_clusters=8).fit(all_colors)
palette = kmeans.cluster_centers_.astype(np.uint8)
# sort values from brightest to darkest
idx = np.argsort(palette.sum(axis=1))[::-1]
return palette[idx].reshape(-1, 8, 3)
def save_dominant_colors(img, filename):
palette = dominant_colors(img)
plt.title(filename)
plt.imshow(palette)
plt.savefig('colors_' + filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment