本文小编为大家详细介绍“OpenCV连通域数量统计实例分析”,内容详细,步骤清晰,细节处理妥当,希望这篇“OpenCV连通域数量统计实例分析”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
核心代码
int connectionDetect(Mat &src, Mat &dst, vector<Feather> &featherList){int rows = src.rows;int cols = src.cols;int labelValue = 0;Point seed, neighbor;stack<Point> pointStack;// 用于计算连通域的面积int area = 0; // 连通域的左边界,即外接最小矩形的左边框,横坐标值,依此类推int leftBoundary = 0; int rightBoundary = 0;int topBoundary = 0;int bottomBoundary = 0;// 外接矩形框Rect box; Feather feather;vector<stack<Point>> points;featherList.clear();dst.release();dst = src.clone();for (int i = 0; i < rows; i++){uchar *pRow = dst.ptr<uchar>(i);for (int j = 0; j < cols; j++){if (pRow[j] == 255){area = 0;// labelValue最大为254,最小为1.labelValue++; // Point(横坐标,纵坐标)seed = Point(j, i); dst.at<uchar>(seed) = labelValue;pointStack.push(seed);area++;leftBoundary = seed.x;rightBoundary = seed.x;topBoundary = seed.y;bottomBoundary = seed.y;while (!pointStack.empty()){neighbor = Point(seed.x + 1, seed.y);if ((seed.x != (cols - 1)) && (dst.at<uchar>(neighbor) == 255)){dst.at<uchar>(neighbor) = labelValue;pointStack.push(neighbor);area++;if (rightBoundary < neighbor.x)rightBoundary = neighbor.x;}neighbor = Point(seed.x, seed.y + 1);if ((seed.y != (rows - 1)) && (dst.at<uchar>(neighbor) == 255)){dst.at<uchar>(neighbor) = labelValue;pointStack.push(neighbor);area++;if (bottomBoundary < neighbor.y)bottomBoundary = neighbor.y;}neighbor = Point(seed.x - 1, seed.y);if ((seed.x != 0) && (dst.at<uchar>(neighbor) == 255)){dst.at<uchar>(neighbor) = labelValue;pointStack.push(neighbor);area++;if (leftBoundary > neighbor.x)leftBoundary = neighbor.x;}neighbor = Point(seed.x, seed.y - 1);if ((seed.y != 0) && (dst.at<uchar>(neighbor) == 255)){dst.at<uchar>(neighbor) = labelValue;pointStack.push(neighbor);area++;if (topBoundary > neighbor.y)topBoundary = neighbor.y;}seed = pointStack.top();pointStack.pop();}box = Rect(leftBoundary, topBoundary, rightBoundary - leftBoundary, bottomBoundary - topBoundary);feather.area = area;feather.boundingbox = box;feather.label = labelValue;featherList.push_back(feather);}}}return labelValue;}
代码执行说明
<font color=#999AAA >在此不进行实例演示
输入图像为分割后图像
执行结果可根据featherList信息自行绘制矩形框
<hr style=" border:solid; width:100px; height:1px;" color=#000000 size=1">
读到这里,这篇“OpenCV连通域数量统计实例分析”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注编程网行业资讯频道。