今天在弄一个查找连通的最大面积的问题。
要把图像弄成黑底,白字,这样才可以正确找到。
然后调用下边的方法:
RETR_CCOMP:提取所有轮廓,并将轮廓组织成双层结构(two-level hierarchy),顶层为连通域的外围边界,次层位内层边界
#include
#include
using namespace cv;
using namespace std;
int main( int argc, char** argv )
{
Mat src = imread( argv[1] );
int largest_area=0;
int largest_contour_index=0;
Rect bounding_rect;
Mat thr;
cvtColor( src, thr, COLOR_BGR2GRAY ); //Convert to gray
threshold( thr, thr, 125, 255, THRESH_BINARY ); //Threshold the gray
bitwise_not(thr,thr); //这里先变反转颜色
vector > contours; // Vector for storing contours
findContours( thr, contours, RETR_CCOMP, CHAIN_APPROX_SIMPLE ); // Find the contours in the image
for( size_t i = 0; i< contours.size(); i++ ) // iterate through each contour.
{
double area = contourArea( contours[i] ); // Find the area of contour
if( area > largest_area )
{
largest_