-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdominant_color.py
47 lines (33 loc) · 1.12 KB
/
dominant_color.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from PIL import Image
import binascii
import numpy as np
import scipy
NUM_CLUSTERS = 5
# input: PIL image, output: dominant color
def dominant_color(image):
# makes an array of all points, so that it's not a 3D array
array = np.asarray(image)
shape = array.shape
array = array.reshape(np.prod(shape[:2]), shape[2]).astype(float)
mask = np.ones(len(array), dtype=bool)
for i in range(len(array)):
if array[i][3] == 0:
mask[i] = False
array = array[mask]
print("clustering")
codes, dist = scipy.cluster.vq.kmeans(array, NUM_CLUSTERS)
print("cluster centres:\n", codes)
# assign codes
vecs, dist = scipy.cluster.vq.vq(array, codes)
# count occurances
counts, bins = np.histogram(vecs, len(codes))
# find most frequent
index_max = np.argmax(counts)
peak = codes[index_max]
colour = binascii.hexlify(bytearray(int(c) for c in peak)).decode("ascii")
print("most frequent is %s (#%s)" % (peak, colour))
def main():
image = Image.open("images\\nazar-amulet_apple_emoji.png")
dominant_color(image)
if __name__ == "__main__":
main()