如何绘制图像颜色的 KMeans 饼图
Posted
技术标签:
【中文标题】如何绘制图像颜色的 KMeans 饼图【英文标题】:How to plot pie chart of KMeans of image colors 【发布时间】: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)
【问题讨论】:
【参考方案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:\nperc:.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 种颜色示例。
【讨论】:
以上是关于如何绘制图像颜色的 KMeans 饼图的主要内容,如果未能解决你的问题,请参考以下文章
拓端tecdat|R语言在地图上绘制月亮图饼状图数据可视化果蝇基因种群