c++ - 如何在 C++ 中查找图像中的主色和每个簇的百分比?
问题描述
我能够从图像中获得主色,但我无法获得颜色的百分比。
这是我从图像中获取主色的代码:
cv::Matsource_img=cv::imread("detect.bmp",1); // Read image from path
// Serialize, float
cv::Mat data = source_img.reshape(1, source_img.total());
data.convertTo(data, CV_32F);
// Perform k-Means
int k = 10;
std::vector<int> labels;
cv::Mat3f centers;
cv::kmeans(data, k, labels, cv::TermCriteria(), 1, cv::KMEANS_PP_CENTERS, centers);
// Make a poster! (Clustering)
for (int i = 0; i < (int)labels.size(); ++i) {
data.at<float>(i, 0) = centers.at<float>(labels[i], 0);
data.at<float>(i, 1) = centers.at<float>(labels[i], 1);
data.at<float>(i, 2) = centers.at<float>(labels[i], 2);
// qDebug()<<labels.size();
}
// Un-Serialize, un-float
cv::Mat destination = data.reshape(3, source_img.rows);
destination.convertTo(source_img, CV_8UC3);
std::sort(centers.begin(), centers.end(),
[](const cv::Vec3f &a, const cv::Vec3f &b) -> bool
{ return a[0] + a[1] + a[2] > b[0] + b[1] + b[2]; }
);
// Paint!
QLabel *palette[6] = {ui->b_1, ui->b_2, ui->b_3, ui->b_4, ui->b_5, ui->b_6};
const int p = 0; // Offset
for(int i = 0; i < 6; ++i) {
// Set back color of label. Lazy ass way to show the colors
std::stringstream back_clr;
back_clr << centers.at<float>(i + p, 2) << "," << centers.at<float>(i + p, 1) << "," << centers.at<float>(i + p, 0);
palette[i]->setStyleSheet(QString::fromStdString("background-color:rgb(" + back_clr.str() + ");"));
qInfo()<< QString::fromStdString(back_clr.str() );
}
这是我的输出:
Screenshot from 2021-04-09 16-51-30.png
"238.594,229.237,205.951"
"213.832,204.984,180.845"
"216.373,190.585,84.8002"
"218.931,132.845,105.804"
"138.95,143.804,118.714"
"198.743,110.853,46.7355"
但我想要这样的输出:
[238.59435545 229.23386034 205.94674433] 29.34%
[213.67154468 204.84374578 180.77144429] 21.07%
[198.76836914 110.87256368 46.76773957] 7.76%
[39.94140346 42.37245936 36.42510903] 7.68%
[216.17736047 190.52489076 84.93423309] 7.36%
[ 83.247557 108.82634188 70.66370203] 7.15%
[82.05183941 60.05586475 55.07991179] 5.87%
[218.7735931 132.99684942 105.99257623] 5.62%
[ 41.73549837 87.24996989 139.9000843 ] 5.07%
[132.72742222 139.51450372 113.63158587] 3.09%
解决方案
您想计算每个标签在 中出现的频率labels
,即标签在 中出现的频率为0
29.34% labels
。这只是一个std::count
除以labels.size()
推荐阅读
- typescript - 将数组转换为映射类型的元组的 Typescript 函数签名
- angular - 当我在 Angular 项目中执行 npm install 时创建/修改了哪些文件?(在我的情况下,角度为 8)
- android - 如何遍历数据绑定器已知的所有视图?
- python - 导入 Tkinter 文件后如何继续运行代码?
- java - 有人能告诉我为什么我的代码中出现 java.lang.ArrayIndexOutOfBoundsException 错误吗?
- arrays - 如何在 Julia 中连接不同大小的向量?
- python - 有没有办法让 python 检测字母字符并产生错误消息?
- r - renderPlot 在视图中输出绘图,而不是浏览器
- c++ - 具有参数的模板的特化
- python - 为什么静音命令在 Discord.py 中不起作用?