python opencv 利用kmeans提取图像主颜色

#包
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_) # count how many pixels per cluster
    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
#K聚类
clt = KMeans(n_clusters=10)

#循环读取文件
n=10
while n<=20:
    my_file = Path('你的路径')
    if my_file.exists():
#         print('你的路径 存在')
        print('-------------------------------------------')
        print(str(n) +'.jpg:')
        # 读取图像和RGB信息
        # COLOR_BGR2RGB :转换颜色空间
        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

你可能感兴趣的:(python,opencv)