根据现有的标签(而不是二进制图像)查找使用 OpenCV 连接的组件

Find connected components with OpenCV based on existed labeling, but not binary image

本文关键字:查找 图像 连接 OpenCV 二进制 组件 标签      更新时间:2023-10-16

OpenCV有一个在二进制图像上查找连接组件的功能:(cv::connectedComponents(((,但它不考虑现有的标签。仅在具有相同标签的像素内查找连接组件的正确方法是什么?

例如,我有代码:

Mat test = Mat::zeros(1, 4, DataType<int>::type);
test.at<int>(0, 0) = 1;
test.at<int>(0, 1) = 2;
test.at<int>(0, 2) = 0;
test.at<int>(0, 3) = 1;
test.convertTo(test, CV_8U);
connectedComponents(test, test);
std::cout << test << std::endl;

它有输入矩阵[1, 2, 0, 1],并将其标记为[1, 1, 0, 2]。但我想得到[1, 2, 0, 3].有没有办法用OpenCV做到这一点?

我的问题解决方案:

Mat connected_components(const Mat &labels)
{
Mat res, input;
labels.convertTo(input, CV_8U);
connectedComponents(input, res);
res.convertTo(res, DataType<int>::type);
double n_labels;
minMaxLoc(res, nullptr, &n_labels);
res += labels * (n_labels + 1);
std::map<int, int> new_ids;
for (int row = 0; row < labels.rows; ++row)
{
auto row_res_data = res.ptr<int>(row);
for (int col = 0; col < labels.cols; ++col)
{
auto cur_lab = row_res_data[col];
if (cur_lab == 0)
continue;
auto iter = new_ids.emplace(cur_lab, new_ids.size() + 1);
row_res_data[col] = iter.first->second;
}
}
return res;
}