存档

文章标签 ‘算法’

Python 提取图片的主体颜色

2020年11月5日 没有评论

如果要计算一个图片的平均色或者是主题色,过去的做法是遍历图片的像素点,然后分别针对R\G\B做加权平均。但是这样会产生一个意料之外的结果,就是这个平均值的颜色,在这个图片上根本就没有出现过。它仅仅是数学意义上的平均值。

所以另外一种思路就是根据图片里的颜色做聚类分析,只在已经存在的颜色范围里计算。这里可以使用 k-means 传统机器学习算法。

from skimage import io
from sklearn.cluster import KMeans
import numpy as np

# k-means中的k值,即选择几个中心点
k = 3

img = io.imread('city.jpg')
# 转换数据维度
img_ori_shape = img.shape
img1 = img.reshape((img_ori_shape[0] * img_ori_shape[1], img_ori_shape[2]))
img_shape = img1.shape

# 获取图片色彩层数
n_channels = img_shape[1]
# 构造聚类器
estimator = KMeans(n_clusters=k, max_iter= 4000, init='k-means++', n_init=50)
estimator.fit(img1) # 聚类
centroids = estimator.cluster_centers_  # 获取聚类中心

# 生成一个可视化矩阵
result = []
result_width = 200
result_height_per_center = 80
for center_index in range(k):
    result.append(np.full((result_width * result_height_per_center, n_channels), 
    centroids[center_index], dtype=int))
result = np.array(result)
result = result.reshape((result_height_per_center * k, result_width, n_channels))
# 保存矩阵到图片
io.imsave('result.jpg', result)

最后放上测试使用的图片,有兴趣的同学可以试一试,顺序有可能不一样,但是颜色应该是这几个。

分类: Python, 日常 标签: