OpenCV联通组件扫描

注:黑色背景

void ccl_demo()
{

	QString appPath = QCoreApplication::applicationDirPath();
	QString imagePath = appPath + "/rice.png";
	Mat img = cv::imread(imagePath.toStdString());
	if (img.empty()) {
		return;
	}
	namedWindow("input", WINDOW_AUTOSIZE);
	imshow("input", img);

	//高斯模糊:降噪
	GaussianBlur(img, img, Size(3, 3),0);

	//To gray image
	Mat gray, binary;
	cvtColor(img, gray, COLOR_BGR2GRAY);
	imshow("gray", gray);

	//OTSU
	double m_otsu = threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
	imshow("BINARY", binary);

	ccl_stats_demo(binary);

}
void ccl_stats_demo(Mat &image)
{
	Mat labels = Mat::zeros(image.size(), CV_32S);
	Mat stats, centrolds;
	int num_labels = connectedComponentsWithStats(image,labels,stats,centrolds,8, CV_32S, CCL_DEFAULT);

	vector<Vec3b> colorTable(num_labels);

	RNG rng(12345);
	//background color
	colorTable[0] = Vec3b(0, 0, 0);
	
	for (int i = 1; i < num_labels; i++)
	{
		colorTable[i] = Vec3b(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));
	}
	Mat result = Mat::zeros(image.size(), CV_8UC3);
	int w = result.cols;
	int h = result.rows;
	for (int row = 0; row < h; row++)
	{
		for (int col = 0; col < w; col++)
		{
			int label = labels.at<int>(row, col);
			result.at<Vec3b>(row, col) = colorTable[label];
		}
	}

	for (int i = 1; i < num_labels; i++)
	{
		//center
		int cx = centrolds.at<double>(i, 0);
		int cy = centrolds.at<double>(i, 1);
		//rectangle
		int x = stats.at<int>(i, CC_STAT_LEFT);
		int y = stats.at<int>(i, CC_STAT_TOP);
		int w = stats.at<int>(i, CC_STAT_WIDTH);
		int h = stats.at<int>(i, CC_STAT_HEIGHT);
		int area = stats.at<int>(i, CC_STAT_AREA);

		circle(result, Point(cx, cy), 3, Scalar(0, 0, 255), 2, 8, 0);
		Rect box(x, y, w, h);
		rectangle(result, box, Scalar(0, 255, 0), 2, 8, 0);
		putText(result, format("%d", area), Point(x,y), FONT_HERSHEY_PLAIN, 1.0, Scalar(0, 255, 255), 1);
	}

	putText(result, format("number:%d", num_labels-1), Point(10, 10), FONT_HERSHEY_PLAIN, 1.0, Scalar(0, 0, 255), 1);
	imshow("CCL demo", result);
}

相关推荐

  1. OpenCV联通组件扫描

    2024-03-31 10:46:06       18 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-31 10:46:06       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-31 10:46:06       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-31 10:46:06       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-31 10:46:06       20 阅读

热门阅读

  1. Leetcode 643. 子数组最大平均数 I

    2024-03-31 10:46:06       17 阅读
  2. Timofey and a tree(思维题)

    2024-03-31 10:46:06       16 阅读
  3. 【二十六】【算法分析与设计】分治(1)

    2024-03-31 10:46:06       17 阅读
  4. [leetcode] 290. 单词规律

    2024-03-31 10:46:06       15 阅读
  5. 好用的编辑器Typora分享

    2024-03-31 10:46:06       20 阅读
  6. 有线电视网 题解

    2024-03-31 10:46:06       14 阅读
  7. 蓝桥杯算法题-发现环

    2024-03-31 10:46:06       17 阅读
  8. Unity WebRequest 变得简单

    2024-03-31 10:46:06       15 阅读
  9. Nginx入门--初识Nginx的架构

    2024-03-31 10:46:06       16 阅读