After long grunts, I kind of worked out what you want. Please note that there is still some assertion about what you mean by “strict bounding box”: the sample in the original question does not provide a satisfactory description that you gave:
But the rectangles should be combined only if the bounding box matches the size of the two rectangles, i.e. the area of the bounding box must be exactly the same as the size of the areas of the two source rectangles. If the area of rectangle 1 is a1, and the area of rect2 is a2, and the area of the bounding rectangle is a3, then a1 + a2 = a3.
This implementation should give you a lot of ideas, and I'm sure you know how to write
r.area() == a.area() + b.area()
if you really wanted to.
// Final proposal: combine adjacent rectangles, // if they are 'flush': almost touching
Output:
sample from original question a: (0,0)-(320,119) b: (0,120)-(320,239) r: (0,0)-(320,239) sample from the comment a: (0,0)-(1,320) b: (0,0)-(2,320) r: (0,0)-(2,320)
source share