Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you calculate the percentage overlap of two rectangles?

I wrote a drawing function that draws various on-screen sprites. These sprites can only overlap up to a point. If they have to much overlap, they become too obscured. As a result I need to detect when these sprites are too much overlapped. Luckily, the problem is simplified in that the sprites can be treated as orthogonal rectangles. I'd like to know by how much these rectangles overlap. Right now, I just brute force it by testing each pixel in one rectangle to see if the other contains it. I count these and calculate the percentage overlap. I think there's probably a better, less brute force approach. What algorithm can I use to determine this?

I'm using wxwidgets.

like image 807
max Avatar asked Sep 17 '09 19:09

max


People also ask

How do you calculate overlap percentage?

And, we do that by calculating the Intersection area of the two polygons and the Union area of the two polygons. And then, getting the value of those areas from the attribute table and then dividing them, Intersect divided by Union. And that gives us the percentage overlap.

How do you find the overlapping area of two rectangles?

We basically add areas of two rectangles. This includes the intersecting part twice, so we subtract the area of intersecting part. Similarly, we can compute area of 2nd rectangle. If the x_distance or y_distance is negative, then the two rectangles do not intersect.

How do you find overlap?

Overlap = min(A2, B2) - max(A1, B1) + 1. In other words, the overlap of two integer intervals is a difference between the minimum value of the two upper boundaries and the maximum value of the two lower boundaries, plus 1.


1 Answers

The results depends on how you define overlapping percentage, to keep it symmetric, I would code it like this:

double CalculatePercentOverlap(const wxRect& rect1, const wxRect& rect2)
{
  wxRect inter = rect1.Intersect(rect2);
  if (inter.IsEmpty())
    return 0;
  return (double)(inter.GetWidth()*inter.GetHeight()) * 2.0 /
    (double)(rect1.GetWidth()*rect1.GetHeight() + 
             rect2.GetWidth()*rect2.GetHeight());
}
like image 163
jdehaan Avatar answered Nov 01 '22 04:11

jdehaan