Search code examples
algorithmmathgeometrybounding-box

How much do two rectangles overlap?


I have two rectangles a and b with their sides parallel to the axes of the coordinate system. I have their co-ordinates as x1,y1,x2,y2.

I'm trying to determine, not only do they overlap, but HOW MUCH do they overlap? I'm trying to figure out if they're really the same rectangle give or take a bit of wiggle room. So is their area 95% the same?

Any help in calculating the % of overlap?


Solution

  • Compute the area of the intersection, which is a rectangle too:

    SI = Max(0, Min(XA2, XB2) - Max(XA1, XB1)) * Max(0, Min(YA2, YB2) - Max(YA1, YB1))
    

    From there you compute the area of the union:

    SU = SA + SB - SI
    

    And you can consider the ratio

    SI / SU
    

    (100% in case of a perfect overlap, down to 0%).