【问题标题】:How to plot pie chart of KMeans of image colors如何绘制图像颜色的 KMeans 饼图
【发布时间】:2022-01-10 04:51:34
【问题描述】:

我是计算机视觉方面的新手,我正在尝试绘制一个图来总结图像上的颜色识别。我使用 KMeans 来查找需要检测的像素值。但我想通过调色板或饼图的可视化来改进代码。我想我应该计算落在每个集群上的像素值。但是,我只是卡住了,我不知道该怎么做。

from sklearn.cluster import KMeans 
import matplotlib.pyplot as plt
import numpy as np
from collections import Counter
from skimage import io, color

def kmeans_segementation(image, n_clusters, random_state=0):
    rows, cols, channels = image.shape                                #get the image shape
    X = image.reshape(rows*cols, channels)
    kmeans = KMeans(n_clusters=n_clusters, random_state=0).fit(X)
    labels = kmeans.labels_.reshape(rows, cols)    
    labels = kmeans.cluster_centers_                                  # get group of colors   
    ordered_colors = [labels[key] for key,value in enumerate(labels)]
    print(ordered_colors)
    

img2_rgb = io.imread('frame41.png')

n_clusters = 15

kmeans_segementation(img2_rgb, n_clusters, random_state=0)

【问题讨论】:

    标签: python matplotlib scikit-learn k-means


    【解决方案1】:

    以下代码展示了如何通过 K-Means 算法创建饼图、直方图和重采样图像(图像来自 wikipedia):

    from sklearn.cluster import KMeans
    import matplotlib.pyplot as plt
    import numpy as np
    
    # image_name = 'astronaut.png' # or 'coffee.png' or 'motorcycle_left.png'
    # image = plt.imread('https://raw.githubusercontent.com/scikit-image/scikit-image/main/skimage/data/' + image_name)
    image = plt.imread('wikipedia_rainbow_lorikeet.png')
    
    n_clusters = 9
    rows, cols, channels = image.shape  # get the image shape
    X = image.reshape(rows * cols, channels)
    kmeans = KMeans(n_clusters=n_clusters, random_state=0).fit(X)
    labels = kmeans.labels_.reshape(rows, cols)
    centers = kmeans.cluster_centers_.clip(0, 1)  # get group of colors, make sure they are in the interval 0-1
    
    unique_labels, counts = np.unique(labels, return_counts=True)
    label_order = np.argsort(counts)[::-1]  # descending order
    unique_labels = unique_labels[label_order]
    counts = counts[label_order]
    percentages = counts / counts.sum() * 100
    
    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(ncols=2, nrows=2, figsize=(12, 9))
    
    ax1.imshow(image)
    ax1.axis('off')
    
    color_labels = [f'{label}:\n{perc:.1f} %' for label, perc in zip(unique_labels, percentages)]
    ax2.pie(counts, labels=color_labels, colors=centers[unique_labels])
    
    ax3.imshow(centers[labels])
    ax3.axis('off')
    
    bars = ax4.bar(unique_labels.astype(str), counts, color=centers[unique_labels], edgecolor='black')
    ax4.bar_label(bars, [f'{perc:.1f} %' for perc in percentages])
    for spine in ['top', 'right']:
        ax4.spines[spine].set_visible(False)
    
    plt.tight_layout()
    plt.show()
    

    使用宇航员图像的示例:

    South African flag 的 7 种颜色示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      • 2015-03-29
      • 1970-01-01
      • 2019-01-03
      • 2019-03-18
      • 2019-01-30
      相关资源
      最近更新 更多