/****************************************************************
*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();
}
结果显示为
这篇文章只是对最大轮廓的查找做一些说明,这个只是最基础的效果,想要获得更好的效果,必须在寻找最大轮廓之前对图像进行一些预处理,并且需要一些后续处理