图像形态学—用基本梯度实现轮廓分析

基本的步骤:

  1. 图像形态学梯度
  2. 灰度转化
  3. 全局阈值二值化
  4. 轮廓分析

void morphologyEx_gradient(Mat& src) {
	//1. 图像形态学梯度
	Mat kernel, gradient_Img;
	kernel=getStructuringElement(MORPH_RECT, Size(3, 3));
	morphologyEx(src, gradient_Img, MORPH_GRADIENT, kernel);
	imshow("gradientImg", gradient_Img);

	//2. 灰度转化
	Mat gray;
	cvtColor(src, gray, COLOR_BGR2GRAY);

	//3. 全局阈值二值化
	Mat binary;
	threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
	imshow("binary", binary);

	//4. 轮廓分析
	vector<vector<Point>> contours;
	//4.1 找到轮廓
	findContours(binary, contours, RETR_TREE, CHAIN_APPROX_SIMPLE);
	//4.2 遍历每一个轮廓
	for (size_t i = 0; i < contours.size(); i++)
	{
		//4.3 找到每一个轮廓的正外接矩形
		Rect rect=boundingRect(contours[i]);
		//4.4 每个轮廓的最小外接矩形
		double area = contourArea(contours[i]);
		//4.5 根据条件画出符合要求的轮廓.
		if (area < 200)
			continue;
		int h = rect.height;
		int w = rect.width;
		if (h > (3 * w) || h < 20)
			continue;
		rectangle(src, rect, Scalar(0, 0, 255), 1);
	}
	imshow("dst", src);
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
画出图像的轮廓:

//4.2 遍历每一个轮廓
for (size_t i = 0; i < contours.size(); i++)
{
//4.3 找到每一个轮廓的正外接矩形
Rect rect=boundingRect(contours[i]);
//4.4 每个轮廓的最小外接矩形
double area = contourArea(contours[i]);
//4.5 根据条件画出符合要求的轮廓.
if (area < 200)
	continue;
int h = rect.height;
int w = rect.width;
if (h > (3 * w) || h < 20)
	continue;
drawContours(src, contours, i, Scalar(255, 255, 255), 3);
rectangle(src, rect, Scalar(0, 0, 255), 1);
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值