title: Efficient way to combine intersecting bounding rectangles
body: <p>I'm trying to simplify the following image using OpenCV:</p>
  
  <p><img src="https://i.stack.imgur.com/pGQiF.png" alt="enter image description here"></p>
  
  <p>What we have here are lots of red shapes. Some of them completely contain others. Some of them intersect their neighbors. My goal is to unify all <strong>intersecting</strong> shapes by replacing any two intersecting shapes with the bounding box of their union's polygon. (repeating until there are no more intersecting shapes).</p>
  
  <p>By intersecting I mean also touching. Hope this makes it 100% clear:</p>
  
  <p><img src="https://i.stack.imgur.com/j7Gub.png" alt="enter image description here"></p>
  
  <p>I'm trying to do this efficiently using standard morphology operations; obviously it can be done naively in <code>O(N^2)</code>, but that'll be too slow. Dilation doesn't help because some shapes are only 1px apart and I don't want them merged if they're not intersecting.</p>