首页 > 其他 > 详细

opencv bwlabel

时间:2017-09-01 23:35:30      阅读:461      评论:0      收藏:0      [点我收藏+]
int bwLabel(const Mat& imgBw, Mat& imgLabeled) {
    Mat imgClone = Mat(imgBw.rows + 2, imgBw.cols + 2, imgBw.type(), Scalar(0));
    imgBw.copyTo(imgClone(Rect(1, 1, imgBw.cols, imgBw.rows)));

    imgLabeled.create(imgClone.size(), imgClone.type());
    imgLabeled.setTo(Scalar::all(0));

    vector<vector<Point>>contours;
    vector<Vec4i>hierarchy;
    findContours(imgClone, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE);

    vector<int>contoursLabel(contours.size(), 0);
    int numlab = 1;

    for (vector<vector<Point>>::size_type i = 0; i < contours.size(); i++) {
        if (hierarchy[i][3] >= 0) {
            continue;
        }
        for (vector<Point>::size_type k = 0; k != contours[i].size(); k++) {
            //imgLabeled.at<uchar>(contours[i][k].y, contours[i][k].x) = numlab;
            *(imgLabeled.data + imgLabeled.step[0] * contours[i][k].y + imgLabeled.step[1] * contours[i][k].x) = numlab;
        }
        numlab++;
    }
    for (int i = 0; i < imgLabeled.rows; i++) {
        for (int j = 0; j < imgLabeled.cols; j++) {
            //if (imgClone.at<uchar>(i, j) != 0 && imgLabeled.at<uchar>(i, j) == 0)
            //{
            //    imgLabeled.at<uchar>(i, j) = imgLabeled.at<uchar>(i, j - 1);
            //}
            if (*(imgClone.data + imgClone.step[0] * i + imgClone.step[1] * j) != 0 && *(imgLabeled.data + imgLabeled.step[0] * i + imgLabeled.step[1] * j) == 0) {
                *(imgLabeled.data + imgLabeled.step[0] * i + imgLabeled.step[1] * j) = *(imgLabeled.data + imgLabeled.step[0] * i + imgLabeled.step[1] * (j - 1));
            }
        }
    }
    imgLabeled = imgLabeled(Rect(1, 1, imgBw.cols, imgBw.rows)).clone();
    return numlab - 1;
}

 

opencv bwlabel

原文:http://www.cnblogs.com/jesszhu/p/7465333.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!