Efficiently Group Overlapping Rectangles

2019-07-25 00:49发布

问题:

Best way to group overlapping rectangles? I've tried using OpenCV but the grouprectangles method doesn't work as intended.

I've thought about doing something like this:

L = [every rectangle]
L_next = []
while not L.empty():
    for rectangle in L:
        L.remove(rectangle)
        for other_rectangle in L:
            if rectangle overlaps with other_rectangle:
                L_next += rectangle + other_rectangle
    L = L_next
    L_next = []

Since every rectangle that isn't merged would be dropped from the next list, in the worst case scenario, I'd have n/2 iterations of the outer loop. The two inner loops should execute n and n - 1 times, so that algorithm should be roughly O(n^3) in a worst case scenario, assuming I didn't miss anything and that each step only takes O(1).

Problems:

1) Need to use Equivalence Classes or something to that extent to merge the groups of rectangles correctly. Does Boost have anything like that?

2) This seems like the kind of operation that would have to be done frequently, so I'm surprised about not finding more material on it. What's up with that?

3) Assuming there really is not something already implemented to do this, does anyone have some advice to improve my method?

4) What is the best way to see if two rectangles overlap?

回答1:

I'd look at pygame.Rect.collide methods for a response to your problem. Since rectangle overlapping detection is so common in games, I guess their implementation is quite good in terms of computational complexity.