方法
使用std空间里面的set统计单一出现的颜色,set有去重功能,不需要另外判断。set在内部使用红黑树实现,需要对其元素进行排序,然而Vec3b默认并不支持¥ < < <运算符进行比较,所以需要手动实现一个。
结果验证
存储一个只有蓝色的图像
最后输出的结果,(0, 0, 255) 说明方法有效
Talk is cheap, show me the code
#include<iostream>
#include<vector>
#include<opencv2/opencv.hpp>
#include<set>
using namespace std;
using namespace cv;
// 定义一个比较Vec3b类型的结构体
struct Vec3bCompare {
bool operator() (const Vec3b& a, const Vec3b& b) const {
return (a[2] < b[2]) ||
(a[2] == b[2] && a[1] < b[1]) ||
(a[2] == b[2] && a[1] == b[1] && a[0] < b[0]);
}
};
int main() {
Mat src = imread("./data/blue.png");
if (src.empty()) {
cout << "Image not found!" << endl;
return -1;
}
int height = src.rows, width = src.cols;
// 使用自定义的比较结构体创建set
set<Vec3b, Vec3bCompare> colors;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
Vec3b pixel = src.at<Vec3b>(i, j);
colors.insert(pixel);
}
}
// 打印颜色需要自定义输出方式
//Vec3b原本存储颜色顺序是bgr,这里按照rgb顺序输出
for (const Vec3b& color : colors) {
cout << int(color[2]) << ", " << int(color[1]) << ", " << int(color[0]) << endl;
}
waitKey(0);
return 0;
}