# Revision history [back]

Steps:

1. Find contours(largest contour) in your image.

2. Calculate boundingRect for the largest contour.

Reference :

Creating Bounding boxes and circles for contours

Code:

cvtColor(src,tmp,CV_BGR2GRAY);
vector< vector <Point> > contours; // Vector for storing contour
vector< Vec4i > hierarchy;
int largest_contour_index=0;
int largest_area=0;

findContours( tmp, contours, hierarchy,CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE ); // Find the contours in the image
for( int i = 0; i< contours.size(); i++ ) // iterate through each contour.
{
double a=contourArea( contours[i],false);  //  Find the area of contour
if(a>largest_area){
largest_area=a;
largest_contour_index=i;                //Store the index of largest contour
}
}
Rect R= boundingRect(contours[largest_contour_index]);
rectangle( src, R, Scalar(0,255,0), 2, 8, 0 );
imshow("src",src);

Result:

Steps:

1. Find contours(largest contour) in your image.

2. Calculate boundingRect for the largest contour.

Reference :

Creating Bounding boxes and circles for contours

Code:

Mat tmp;
cvtColor(src,tmp,CV_BGR2GRAY);
vector< vector <Point> > contours; // Vector for storing contour
vector< Vec4i > hierarchy;
int largest_contour_index=0;
int largest_area=0;

findContours( tmp, contours, hierarchy,CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE ); // Find the contours in the image
for( int i = 0; i< contours.size(); i++ ) // iterate through each contour.
{
double a=contourArea( contours[i],false);  //  Find the area of contour
if(a>largest_area){
largest_area=a;
largest_contour_index=i;                //Store the index of largest contour
}
}
Rect R= boundingRect(contours[largest_contour_index]);
rectangle( src, R, Scalar(0,255,0), 2, 8, 0 );
imshow("src",src);

Result: