113 KMeans图像分割—主色彩提取
代码
import numpy as np
import cv2 as cv
image = cv.imread('../images/yuan_test.png')
cv.imshow("input", image)
h, w ,ch = image.shape
print(image.shape)
# 构建图像数据
data = image.reshape((-1,3))
data = np.float32(data)
# 图像分割
criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 10, 1.0)
num_clusters = 4
ret,label,center=cv.kmeans(data, num_clusters, None, criteria, num_clusters, cv.KMEANS_RANDOM_CENTERS)
# 生成主色彩条形卡片
card = np.zeros((50, w, 3), dtype=np.uint8)
clusters = np.zeros([4], dtype=np.int32)
for i in range(len(label)):
clusters[label[i][0]] += 1
clusters = np.float32(clusters) / float(h*w)
center = np.int32(center)
x_offset = 0
for c in range(num_clusters):
dx = np.int(clusters[c] * w)
b = center[c][0]
g = center[c][1]
r = center[c][2]
cv.rectangle(card, (x_offset, 0), (x_offset+dx, 50), (int(b), int(g), int(r)), -1)
x_offset += dx
cv.imshow("color table", card)
cv.waitKey(0)
cv.destroyAllWindows()
实验结果
解释
KMeans分割会计算出每个聚类的像素平均值,根据这个可以得到图像的主色彩RGB分布成分多少,得到各种色彩在图像中的比重,绘制出图像对应的取色卡!这个方面在纺织与填色方面特别有用!主要步骤显示如下:
- 读入图像建立KMenas样本
- 使用KMeans图像分割,指定分类数目
- 统计各个聚类占总像素比率,根据比率建立色卡!
所有内容均来源于贾志刚老师的知识星球——OpenCV研习社,本文为个人整理学习,已获得贾老师授权,有兴趣、有能力的可以加入贾老师的知识星球进行深入学习。