find most used colors in image python

Solutions on MaxInterview for find most used colors in image python by the best coders in the world

showing results for - "find most used colors in image python"
Adriana
22 Oct 2020
1from __future__ import print_function
2import binascii
3import struct
4from PIL import Image
5import numpy as np
6import scipy
7import scipy.misc
8import scipy.cluster
9
10NUM_CLUSTERS = 5
11
12print('reading image')
13im = Image.open('image.jpg')
14im = im.resize((150, 150))      # optional, to reduce time
15ar = np.asarray(im)
16shape = ar.shape
17ar = ar.reshape(np.product(shape[:2]), shape[2]).astype(float)
18
19print('finding clusters')
20codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS)
21print('cluster centres:\n', codes)
22
23vecs, dist = scipy.cluster.vq.vq(ar, codes)      # assign codes
24counts, bins = np.histogram(vecs, len(codes))    # count occurrences
25
26index_max = np.argmax(counts)                    # find most frequent
27peak = codes[index_max]
28colour = binascii.hexlify(bytearray(int(c) for c in peak)).decode('ascii') # actual colour, (in HEX)
29print('most frequent is %s (#%s)' % (peak, colour))
30