基于现有标签,但不是二进制图像,使用OpenCV查找连接的组件

时间:2018-05-04 09:53:17

标签: c++ opencv

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做到这一点?

1 个答案:

答案 0 :(得分:0)

我解决问题的方法:

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;
}