首页 > 解决方案 > 多幅图像中的主色

问题描述

我正在尝试找到一种算法来使用 python 找到多个图像的平均主色。我发现了一种算法,可以使用 KMeans 聚类提取单个图像的主色。然后将集群输入直方图函数,最后用 matplot 库绘制。

我对 python 和一般编码相当陌生,我找不到将多个集群数据合并为一个合并多个直方图的方法 最聪明的解决方案是什么?

我试图在一个例子中找到什么。假设您有两张图像,第一张是 50% 青色和 50% 黄色,第二张是 50% 青色和 50% 红色 – 我想要一个组合和加权输出,例如:50% 青色、25% 红色和 25 % 黄色。

到目前为止,这是我的代码

import cv2
import glob
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans


def find_histogram(clt):
    """
    create a histogram with k clusters
    :param: clt
    :return:hist
    """
    numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1)
    (hist, _) = np.histogram(clt.labels_, bins=numLabels)

    hist = hist.astype("float")
    hist /= hist.sum()

    return hist


def plot_colors2(hist, centroids):
    bar = np.zeros((50, 300, 3), dtype="uint8")
    startX = 0

    for (percent, color) in zip(hist, centroids):
        # plot the relative percentage of each cluster
        endX = startX + (percent * 300)
        cv2.rectangle(bar, (int(startX), 0), (int(endX), 180), color.astype("uint8").tolist(), -1)
        startX = endX

    return bar

images = [cv2.imread(file) for file in glob.glob("pics/*.jpg")]


for image in images:
    imageRGB = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    imageReshape = imageRGB.reshape((imageRGB.shape[0] * 
    imageRGB.shape[1],3)) #represent as row*column,channel number

    cluster = KMeans(n_clusters=3) #cluster number
    cluster.fit(imageReshape)

    print(cluster)

    histogram = find_histogram(cluster)
    #print("histogram", histogram)

    bar = plot_colors2(histogram, cluster.cluster_centers_)
    plt.axis("off")
    plt.imshow(bar)
    plt.show()

标签: pythonimage-processinghistogramk-meanscv2

解决方案


推荐阅读