Opencv 每周实例练习 05 轮廓检测

问题:

请添加图片描述
有这样一幅图:

  1. 我们希望抠出手掌mask,
  2. 并用findContours找到上下左右的极值点。

代码实现:

  • 读取图片,转灰度,去除噪声
	cv::Mat src = cv::imread("C:\\D\\opencv\\hand.jpg", -1);
	cv::Mat gray;
	cv::cvtColor(src, gray, cv::COLOR_BGR2GRAY);
	// GaussianBlur
	cv::GaussianBlur(gray, gray, cv::Size(5, 5), 0);
  • 二值化、腐蚀 + 膨胀可以去除噪声区域
	cv::Mat binary, erode_mat, dilate_mat;
	cv::threshold(gray, binary, 45, 255, cv::THRESH_BINARY);

在这里插入图片描述

	cv::erode(binary, erode_mat, cv::Mat(), cv::Point(-1, -1), 2); 
	cv::dilate(erode_mat, dilate_mat, cv::Mat(), cv::Point(-1, -1), 2);

在这里插入图片描述

  • 在阈值图像中找到轮廓,然后抓取最大的
	std::vector<std::vector<Point>> contours;
	cv::findContours(dilate_mat, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
	//计算最大轮廓面积
	int maxarea_index = 0;
	float maxarea = 0;
	for (auto i = 0; i < contours.size(); i++) {
		float area = cv::contourArea(contours[i]); 
		if (maxarea < area) {
			maxarea = area;
			maxarea_index = i;
		}	
	}
  • 确定沿轮廓的最极端点
	int top_num(0), down_num(0), left_num(0), right_num(0);
	Point2f top_p, down_p, left_p, right_p;
	for (auto i = 0; i < contours[maxarea_index].size(); i++) {
		Point2f tep_p = contours[maxarea_index][i];
		if (i == 0) {
			left_num = tep_p.x;
			left_p = tep_p;
			top_num = tep_p.y;
			top_p = tep_p;
		}
		// 极左点
		if (tep_p.x < left_num) {
			left_num = tep_p.x;
			left_p = tep_p;
		}
		//极下点
		else if (tep_p.y > down_num) {
			down_num = tep_p.y;
			down_p = tep_p;
		}
		//极上点
		else if (tep_p.y < top_num) {
			top_num = tep_p.y;
			top_p = tep_p;
		}
		//极右点
		else if (tep_p.x > right_num) {
			right_num = tep_p.x;
			right_p = tep_p;
		}

	}
	cv::circle(src, left_p, 7, cv::Scalar(0, 0, 255));
	cv::circle(src, right_p, 7, cv::Scalar(0, 0, 255));
	cv::circle(src, top_p, 7, cv::Scalar(0, 0, 255));
	cv::circle(src, down_p, 7, cv::Scalar(0, 0, 255));

在这里插入图片描述

  • C++ 11特供版
	left_num = contours[maxarea_index][0].x;
	left_p = contours[maxarea_index][0];
	top_num = contours[maxarea_index][0].y;
	top_p = contours[maxarea_index][0];
	for (auto point : contours[maxarea_index]) {
		// 极左点
		if (point.x < left_num) {
			left_num = point.x;
			left_p = point;
		}
		//极下点
		else if (point.y > down_num) {
			down_num = point.y;
			down_p = point;
		}
		//极上点
		else if (point.y < top_num) {
			top_num = point.y;
			top_p = point;
		}
		//极右点
		else if (point.x > right_num) {
			right_num = point.x;
			right_p = point;
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值