Opencv3实现图像分割之最大连通域算法

/****************************************************************
*http://blog.csdn.net/shaoxiaohu1/article/details/40272875
*****************************************************************/

#include<opencv2\opencv.hpp>
#include<cmath>

using namespace cv;
using namespace std;

int main()
{
	Mat srcImage = imread( "3.jpg" ,0);
	if( !srcImage.data )
	{
		cout << "读取失败" << endl;
		return 0;
	}
	imshow( "原始图" , srcImage );

	// threshold只针对二值化图像
	threshold( srcImage , srcImage , 0.0 , 255.0 ,CV_THRESH_BINARY|CV_THRESH_OTSU ); 

	vector<vector<Point>> contours;
	vector<Vec4i> hierarchy;

	findContours( srcImage , contours , hierarchy , CV_RETR_CCOMP , CV_CHAIN_APPROX_SIMPLE );

	vector<Point> maxcontours ;   //最大轮廓
	double maxArea = 0;

//	vector<vector<Point>>::const_iterator itContours = contours.begin();
	for( size_t i = 0; i < contours.size();i++ )
	{
		double area = contourArea( contours[i] );
		if( area > maxArea )
		{
			maxArea = area;
			maxcontours = contours[i];
		}
	}

	Rect maxRect = boundingRect( maxcontours );  //查找矩形框

	Mat result1 , result2;

	srcImage.copyTo( result1 );
	srcImage.copyTo( result2 );

	for( size_t i = 0; i < contours.size(); i++ )
	{
		Rect r = boundingRect( contours[i] );
		rectangle( result1 , r , Scalar( 255 ) );
	}
	imshow( "all regions" , result1 );
	waitKey();

	rectangle( result2 , maxRect , Scalar( 255 ) );
	imshow( "largest region" , result2 );
	waitKey();
}

结果显示为




这篇文章只是对最大轮廓的查找做一些说明,这个只是最基础的效果,想要获得更好的效果,必须在寻找最大轮廓之前对图像进行一些预处理,并且需要一些后续处理

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值