OpenCV連通域數量統計學習示例

學習目標:

1.輸入圖像為分割結果圖像

2.根據種子填充法思路,遍歷圖像,得到每個連通域外接矩形坐標信息、面積信息

核心代碼

/*
	Input:
		src: 待檢測連通域的二值化圖像
	Output:
		dst: 標記後的圖像
		featherList: 連通域特征的清單(可自行查閱文檔)
	return:
		連通域數量。
*/
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 >在此不進行實例演示

1、 輸入圖像為分割後圖像

2、 執行結果可根據featherList信息自行繪制矩形框

<hr style=" border:solid; width:100px; height:1px;" color=#000000 size=1">

以上就是OpenCV連通域數量統計學習示例的詳細內容,更多關於OpenCV連通域數量統計的資料請關註WalkonNet其它相關文章!

推薦閱讀: