Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Steps:

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

  2. Calculate boundingRect for the largest contour.

Reference :

Finding contours in your image

Creating Bounding boxes and circles for contours

Code:

     Mat src=imread("box.png",1); //Your src  image
     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:

image description

Steps:

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

  2. Calculate boundingRect for the largest contour.

Reference :

Finding contours in your image

Creating Bounding boxes and circles for contours

Code:

     Mat src=imread("box.png",1); //Your src  image
     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:

image description