欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 幼教 > Python案例 | 使用K-means 聚类算法提取图像中的颜色

Python案例 | 使用K-means 聚类算法提取图像中的颜色

2024/10/23 23:19:31 来源:https://blog.csdn.net/ikhui7/article/details/142931224  浏览:    关键词:Python案例 | 使用K-means 聚类算法提取图像中的颜色

假如我们需要提取下图中的颜色,可以通过使用 K-means 聚类算法对图像进行颜色聚类分析,并生成一个基于聚类中心(即最具代表性的颜色)的RGB值和调色板。
在这里插入图片描述

# 通过使用 K-means 聚类算法对图像进行颜色聚类分析,并生成一个基于聚类中心(即最具代表性的颜色)的RGB值和调色板。
# 导入必要的库
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from sklearn.cluster import KMeans# 读取图像
image = mpimg.imread('poland-landscape.jpg')# 获取图像尺寸
w, h, d = image.shape
pixels = image.reshape(w * h, d)# K-means聚类,n_init设置为auto
n_colors = 15
kmeans = KMeans(n_clusters=n_colors, random_state=42, n_init='auto').fit(pixels)# 获取聚类中心(调色板)
palette = np.uint8(kmeans.cluster_centers_)
print(palette)
# 显示调色板
plt.imshow([palette])
plt.axis('off')
plt.savefig('rgb_color_chart.png', dpi=300, bbox_inches='tight')
plt.show()

运行结果如下:
在这里插入图片描述
在这里插入图片描述
聚类得到的15个RGB值如下:

[[  9  43  77][ 70 165 209][145 118  72][ 47 122 160][154 157 153][ 11  26  38][ 79  91  93][212 164  37][ 43  58  64][231 227 217][  6 125 184][216 172 110][ 95  78  39][105 133 146][ 20  78 118]]

参考资料:
https://www.douyin.com/note/7413545987140095241

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com