opencv-113-利用KMeans图像分割进行主色彩提取

知识点

KMeans分割会计算出每个聚类的像素平均值,根据这个可以得到图像的主色彩RGB分布成分多少,得到各种色彩在图像中的比重,绘制出图像对应的取色卡!这个方面在纺织与填色方面特别有用!主要步骤显示如下:

  1. 读入图像建立KMenas样本
  2. 使用KMeans图像分割,指定分类数目
  3. 统计各个聚类占总像素比率,根据比率建立色卡!

代码(c++,python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv) {
Mat src = imread("D:/images/master.jpg");
if (src.empty()) {
printf("could not load image...\n");
return -1;
}
namedWindow("input image", WINDOW_AUTOSIZE);
imshow("input image", src);

int width = src.cols;
int height = src.rows;
int dims = src.channels();

// 初始化定义
int sampleCount = width*height;
int clusterCount = 4;
Mat labels;
Mat centers;

// RGB 数据转换到样本数据
Mat sample_data = src.reshape(3, sampleCount);
Mat data;
sample_data.convertTo(data, CV_32F);

// 运行K-Means
TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 10, 0.1);
kmeans(data, clusterCount, labels, criteria, clusterCount, KMEANS_PP_CENTERS, centers);

Mat card = Mat::zeros(Size(width, 50), CV_8UC3);
vector<float> clusters(clusterCount);
for (int i = 0; i < labels.rows; i++) {
clusters[labels.at<int>(i, 0)]++;
}
for (int i = 0; i < clusters.size(); i++) {
clusters[i] = clusters[i] / sampleCount;
}
int x_offset = 0;
for (int x = 0; x < clusterCount; x++) {
Rect rect;
rect.x = x_offset;
rect.y = 0;
rect.height = 50;
rect.width = round(clusters[x] * width);
x_offset += rect.width;
int b = centers.at<float>(x, 0);
int g = centers.at<float>(x, 1);
int r = centers.at<float>(x, 2);
rectangle(card, rect, Scalar(b, g, r), -1, 8, 0);
}

imshow("Image Color Card", card);
waitKey(0);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"""
利用KMeans图像分割进行主色彩提取
"""

import cv2 as cv
import numpy as np

image = cv.imread('images/toux.jpg')
cv.imshow("input", image)
h, w, ch = 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()

结果

代码地址

github