Ask Your Question
0

Calc a bounding box with a binarized image?

asked 2014-02-10 16:41:09 -0600

yes123 gravatar image

updated 2014-02-10 16:43:34 -0600

This is an interesting task, but sadly I couldn't find any detailed answers. Let's say I have binarized an image with an object that can be like this (with some rumors):

image description

Which would be the best way (and maybe the fastest) to determine the bounding box around that triangle? Something like this:

image description

Possibily without using cvBlobLib or other third party

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
5

answered 2014-02-11 00:06:49 -0600

Haris gravatar image

updated 2014-02-11 00:08:20 -0600

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

edit flag offensive delete link more

Question Tools

Stats

Asked: 2014-02-10 16:41:09 -0600

Seen: 3,240 times

Last updated: Feb 11 '14