Search code examples
c++opencvrectanglesobject-detection

Merging Overlapping Rectangle in OpenCV


I'm using OpenCV 3.0. I've made a car detection program and I keep running into the problem of overlapping bounding boxes:

enter image description here

Is there a way to merge overlapping bounding boxes as described on the images below? I've used rectangle(frame, Point(x1, y1), Point(x2, y2), Scalar(255,255,255)); to draw those bounding boxes. I've searched for answer from similiar threads but I can't find them helpful. I'd like to form a single outer bounding rectangle after merging those bounding boxes.


Solution

  • Problem

    Seems as if you are displaying each contour you are getting. You don't have to do that. Follow the algorithm and code given below.

    Algorithm

    In this case what you can do is iterate through each contour that you detect and select the biggest boundingRect. You don't have to display each contour you detect.

    Here is a code that you can use.

    Code

    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
           bounding_rect=boundingRect(contours[i]); // Find the bounding rectangle for biggest contour
           }
    
          }
    

    Regards