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; }
时间: 2024-10-12 17:44:14