opencv笔记(十九)——提取连通区域轮廓

连通区域指的是二值图像中相连像素组成的形状。而内、外轮廓的概念及opencv1中如何提取二值图像的轮廓见我的这篇博客:http://blog.csdn.net/lu597203933/article/details/14489225

 轮廓的简单提取算法如下:

       系统性地扫描图像直到遇到连通区域的一个点,以它为起始点,跟踪它的轮廓,标记边界上的像素。当轮廓完整闭合,扫描回到上一个位置,直到再次发现新的成分。

代码:

#include <iostream>
#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
 
using namespace std;
using namespace cv;
 
// 移除过小或过大的轮廓
void getSizeContours(vector<vector<Point>> &contours)
{
	int cmin = 100;   // 最小轮廓长度
	int cmax = 1000;   // 最大轮廓长度
	vector<vector<Point>>::const_iterator itc = contours.begin();
	while(itc != contours.end())
	{
		if((itc->size()) < cmin || (itc->size()) > cmax)
		{
			itc = contours.erase(itc);
		}
		else ++ itc;
	}
}
 
// 计算连通区域的轮廓,即二值图像中相连像素的形状
 
int main()
{
	Mat image = imread("E:\\opencv2cv\\lesson7\\Debug\\55.png",0);
	if(!image.data)
	{
		cout << "Fail to load image" << endl;
		return 0;
	}
	Mat imageShold;
	threshold(image, imageShold, 100, 255, THRESH_BINARY);   // 必须进行二值化
	vector<vector<Point>> contours;
	//CV_CHAIN_APPROX_NONE  获取每个轮廓每个像素点
	findContours(imageShold, contours, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE, cvPoint(0,0));
	getSizeContours(contours);
	cout << contours.size() << endl;
	Mat result(image.size(), CV_8U, Scalar(255));
	drawContours(result, contours, -1, Scalar(0), 2);   // -1 表示所有轮廓
	namedWindow("result");
	imshow("result", result);
	namedWindow("image");
	imshow("image", image);
	waitKey(0);
	return 0;
}

结果:

未移除过大多小的轮廓前:

移除后:

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值