title: Finding the union of multiple overlapping rectangles - OpenCV python
body: <p>I have several overlapping bounding boxes that encompass a single object, however they overlap minimally in some places. Taken as a whole, they encompass the entire object, but openCV's groupRectangles function does not return a box encompassing the object. The bounding boxes I have are shown in blue, and bounding boxes I would like to return are shown in red here</p>
  
  <p><img src="https://i.stack.imgur.com/CJ6mB.png" alt=""></p>
  
  <p>I would like to get the union of only the overlapping rectangles but am unsure about how to iterate through the list without combining every rectangle.
  I have union and intersect functions shown below, and a list of the rectangles represented by (x y w h), where x and y are the coordinates of the top left corner of the box.</p>
  
  <pre><code>def union(a,b):
    x = min(a[0], b[0])
    y = min(a[1], b[1])
    w = max(a[0]+a[2], b[0]+b[2]) - x
    h = max(a[1]+a[3], b[1]+b[3]) - y
    return (x, y, w, h)
  
  def intersection(a,b):
    x = max(a[0], b[0])
    y = max(a[1], b[1])
    w = min(a[0]+a[2], b[0]+b[2]) - x
    h = min(a[1]+a[3], b[1]+b[3]) - y
    if w&lt;0 or h&lt;0: return () # or (0,0,0,0) ?
    return (x, y, w, h)
  </code></pre>
  
  <p>My function for combining is currently as follows:</p>
  
  <pre><code>def combine_boxes(boxes):
      noIntersect = False
      while noIntersect == False and len(boxes) &gt; 1:
          a = boxes[0]
          print a
          listBoxes = boxes[1:]
          print listBoxes
          index = 0
          for b in listBoxes:
              if intersection(a, b):
                  newBox = union(a,b)
                  listBoxes[index] = newBox
                  boxes = listBoxes
                  noIntersect = False
                  index = index + 1
                  break
              noIntersect = True
              index = index + 1
  
      print boxes
      return boxes.astype("int")
  </code></pre>
  
  <p>This gets most of the way there, as shown here</p>
  
  <p><img src="https://i.stack.imgur.com/Lt1yY.png" alt=""></p>
  
  <p>there are still a few nested bounding boxes that I'm not sure how to continue iterating through. </p>