# Calc a bounding box with a binarized image?

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):

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

Possibily without using cvBlobLib or other third party

edit retag close merge delete

Sort by ยป oldest newest most voted

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 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:

more