首頁 > 軟體

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

2022-06-07 14:07:02

學習目標:

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連通域數量統計的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com