-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfinalass1.py
More file actions
51 lines (44 loc) · 1.78 KB
/
finalass1.py
File metadata and controls
51 lines (44 loc) · 1.78 KB
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
import cv2, numpy as np
from sklearn.cluster import KMeans
from matplotlib import pyplot as plt
per=[]
col=[]
def visualize_colors(cluster, centroids):
# Get the number of different clusters, create histogram, and normalize
labels = np.arange(0, len(np.unique(cluster.labels_)) + 1)
(hist, _) = np.histogram(cluster.labels_, bins = labels)
hist = hist.astype("float")
hist /= hist.sum()
# Create frequency rect and iterate through each cluster's color and percentage
rect = np.zeros((50, 300, 3), dtype=np.uint8)
colors = sorted([(percent, color) for (percent, color) in zip(hist, centroids)])
start = 0
for (percent, color) in colors:
print(color, "{:0.2f}%".format(percent * 100))
end = start + (percent * 300)
cv2.rectangle(rect, (int(start), 0), (int(end), 50),\
color.astype("uint8").tolist(), -1)
start = end
per.append("{:0.2f}".format(percent * 100))
col.append(color/255)
return rect
# Load image and convert to a list of pixels
image = cv2.imread(r'C:\Users\Dell\Desktop\kr.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(image)
plt.show()
reshape = image.reshape((image.shape[0] * image.shape[1], 3))
# Find and display most dominant colors
cluster = KMeans(n_clusters=5).fit(reshape)
visualize = visualize_colors(cluster, cluster.cluster_centers_)
plt.imshow(visualize)
plt.show()
# print(per)
# print(col)
lab=['color 1','color 2','color 3','color 4','color 5']
plt.title('Top 5 most prominent colours', fontsize = 24)
plt.legend(lab, loc = 'upper right')
explode = (0, 0, 0, 0, 0.1) # only "explode" the 2nd slice (i.e. 'Hogs')
plt.pie(per,explode=explode,colors=col,labels=lab,shadow=True)
plt.tight_layout()
plt.show()