Adi Shavit
Adi Shavit

Reputation: 17275

Label Images in OpenCV

Given the same binary input image (up to inversion), is there a guarantee that the labels in the images returned by all the following functions are all consistent?

Does this appear in the docs anywhere?

Upvotes: 1

Views: 9093

Answers (1)

Miki
Miki

Reputation: 41765

If you pass to distanceTransform a binary image inverted with respect to connectedComponents or connectedComponentsWithStats, the labels are computed the same way and will be consistent.

I was not able to find any reference in the doc, but the labels will be computed by the same algorithm (connectedComponents_sub1) in all cases.

connectedComponents[WithStats]

int cv::connectedComponents(InputArray _img, OutputArray _labels, int connectivity, int ltype){
    const cv::Mat img = _img.getMat();
    _labels.create(img.size(), CV_MAT_DEPTH(ltype));
    cv::Mat labels = _labels.getMat();
    connectedcomponents::NoOp sop;
    if(ltype == CV_16U){
        return connectedComponents_sub1(img, labels, connectivity, sop);
    }else if(ltype == CV_32S){
        return connectedComponents_sub1(img, labels, connectivity, sop);
    }else{
        CV_Error(CV_StsUnsupportedFormat, "the type of labels must be 16u or 32s");
        return 0;
    }
}


int cv::connectedComponentsWithStats(InputArray _img, OutputArray _labels, OutputArray statsv,
                                     OutputArray centroids, int connectivity, int ltype)
{
    const cv::Mat img = _img.getMat();
    _labels.create(img.size(), CV_MAT_DEPTH(ltype));
    cv::Mat labels = _labels.getMat();
    connectedcomponents::CCStatsOp sop(statsv, centroids);
    if(ltype == CV_16U){
        return connectedComponents_sub1(img, labels, connectivity, sop);
    }else if(ltype == CV_32S){
        return connectedComponents_sub1(img, labels, connectivity, sop);
    }else{
        CV_Error(CV_StsUnsupportedFormat, "the type of labels must be 16u or 32s");
        return 0;
    }
}

As you can see, the labeling part is performed by the connectedComponents_sub1 function in both cases. The only difference between the two is the statistic computation: connectedcomponents::NoOp versus connectedcomponents::CCStatsOp, not relevant for label computation.

distanceTransform

void cv::distanceTransform( InputArray _src, OutputArray _dst, OutputArray _labels,
                        int distType, int maskSize, int labelType )
{
    ...
    if( labelType == CV_DIST_LABEL_CCOMP )
    {
        Mat zpix = src == 0;
        connectedComponents(zpix, labels, 8, CV_32S);
    }
    ...
}

The labels are computed internally by the function connectedComponents.

Upvotes: 1

Related Questions