OpenCV connectedComponentsWithStats函数获取最大连通域

利用 connectedComponentsWithStats函数返回的stats中连通域的面积,选出最大的连通域,并将其单独绘制出来。

Mat labels, stats, centroids;
	int nccomps = connectedComponentsWithStats(midImg2, labels, stats, centroids, 4, CV_16U);
	
	int stats_rows = stats.rows;
	int maximum = 0;
	int max_idx = 0;
	for (int i = 1; i < stats_rows;i++) //取得最大连通域标号
	{
		if (stats.at<int>(i, 4)>maximum)
		{
			maximum = stats.at<int>(i, 4);
			max_idx = i;
		}
	}

	//由索引号将最大连通域标为255
	int rows = labels.rows;
	int cols = labels.cols;
	for (int row = 0; row < rows; row++)
	{
		for (int col = 0; col < cols; col++)
		{
			if (labels.at<unsigned short>(row, col) == max_idx)
			{
				labels.at<unsigned short>(row, col) = 255;
			}
			else
			{
				labels.at<unsigned short>(row, col) = 0;
			}
		}
	}
	//将图像改为CV_8U格式
	Mat dstImg;
	labels.convertTo(dstImg, CV_8U);
	resize(dstImg, dstImg, Size(), 0.4, 0.4);
	imshow("dstImg", dstImg);

你可能感兴趣的:(opencv,人工智能,计算机视觉,c++)