import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
import PIL
%matplotlib inline
from collections import Counter
def calculate_perc(k_cluster):
width = 300
palette = np.zeros((50, width, 3), np.uint8)
n_pixels = len(k_cluster.labels_)
counter = Counter(k_cluster.labels_)
perc = {}
for i in counter:
perc[i] = np.round(counter[i]/n_pixels, 2)
perc = dict(sorted(perc.items()))
step = 0
for idx, centers in enumerate(k_cluster.cluster_centers_):
palette[:, step:int(step + perc[idx]*width+1), :] = centers
step += int(perc[idx]*width+1)
return palette
from sklearn.cluster import KMeans
clt = KMeans(n_clusters=10)
n=10
while n<=20:
my_file = Path('你的路径')
if my_file.exists():
print('-------------------------------------------')
print(str(n) +'.jpg:')
img = cv.imread('你的路径')
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
clt_1 = clt.fit(img.reshape(-1, 3))
plt.imshow(calculate_perc(clt_1))
plt.show()
print('--------------------------------------------')
print(' ')
else:
print('你的路径 不存在!')
n+=1