-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDominantColors.py
91 lines (56 loc) · 2.02 KB
/
DominantColors.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import cv2
from sklearn.cluster import KMeans
import numpy as np
class DominantColors:
CLUSTERS = None
IMAGE = None
COLORS = None
LABELS = None
def __init__(self, image, clusters=3):
self.CLUSTERS = clusters
self.IMAGE = image
def dominantColors(self):
# read image
img = cv2.imread(self.IMAGE)
#img = cv2.imdecode(self.IMAGE,1)
# convert to rgb from bgr
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# reshaping to a list of pixels
img = img.reshape((img.shape[0] * img.shape[1], 3))
# save image after operations
self.IMAGE = img
# using k-means to cluster pixels
kmeans = KMeans(n_clusters=self.CLUSTERS)
kmeans.fit(img)
# the cluster centers are our dominant colors.
self.COLORS = kmeans.cluster_centers_
# save labels
self.LABELS = kmeans.labels_
# returning after converting to integer from float
return self.COLORS.astype(int)
def plotHistogram(self):
# labels form 0 to no. of clusters
numLabels = np.arange(0, self.CLUSTERS + 1)
# create frequency count tables
(hist, _) = np.histogram(self.LABELS, bins=numLabels)
hist = hist.astype("float")
hist /= hist.sum()
# appending frequencies to cluster centers
colors = self.COLORS
# descending order sorting as per frequency count
colors = colors[(-hist).argsort()]
hist = hist[(-hist).argsort()]
# creating empty chart
chart = np.zeros((50, 500, 3), np.uint8)
start = 0
# creating color rectangles
for i in range(self.CLUSTERS):
end = start + hist[i] * 500
# getting rgb values
r = colors[i][0]
g = colors[i][1]
b = colors[i][2]
# using cv2.rectangle to plot colors
cv2.rectangle(chart, (int(start), 0), (int(end), 50), (r, g, b), -1)
start = end
return chart