fanfuhan OpenCV 教學113 ~ opencv-113-利用KMeans圖像分割進行主色彩提取 [顏色 數量統計]
fanfuhan OpenCV 教學113 ~ opencv-113-利用KMeans圖像分割進行主色彩提取 [顏色 數量統計]
資料來源: https://fanfuhan.github.io/
https://fanfuhan.github.io/2019/05/24/opencv-113/
GITHUB:https://github.com/jash-git/fanfuhan_ML_OpenCV
KMeans分割會計算出每個聚類的預定值,根據這個可以得到圖像的主色彩RGB分佈多少,得到各種色彩在圖像中的比重,替換出圖像對應的取色卡!這個方面在紡織與填色方面特別有用!主要步驟顯示如下:
01.讀入圖像建立KMenas樣本
02.使用KMeans圖像分割,指定分類數
03.統計各個聚類占總預期比率,根據比率建立色卡!
C++
#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; }
Python
""" 利用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()