import numpy as np
import Image
def palette(img):
"""
Return palette in descending order of frequency
"""
arr = np.asarray(img)
palette, index = np.unique(asvoid(arr).ravel(), return_inverse=True)
palette = palette.view(arr.dtype).reshape(-1, arr.shape[-1])
count = np.bincount(index)
order = np.argsort(count)
return palette[order[::-1]]
def asvoid(arr):
"""View the array as dtype np.void (bytes)
This collapses ND-arrays to 1D-arrays, so you can perform 1D operations on them.
http://stackoverflow.com/a/16216866/190597 (Jaime)
http://stackoverflow.com/a/16840350/190597 (Jaime)
Warning:
>>> asvoid([-0.]) == asvoid([0.])
array([False], dtype=bool)
"""
arr = np.ascontiguousarray(arr)
return arr.view(np.dtype((np.void, arr.dtype.itemsize * arr.shape[-1])))
img = Image.open(FILENAME, 'r').convert('RGB')
print(palette(img))
palette(img)
returns a numpy array. Each row can be interpreted as a color:
[[255 255 255]
[ 0 0 0]
[254 254 254]
...,
[213 213 167]
[213 213 169]
[199 131 43]]
To get the top ten colors:
palette(img)[:10]