Search code examples
pythonnumpymatplotlibpolygonshapely

Calculate overlapped area between two rectangles


enter image description here

I want to calculate the overlapped area "THE GRAY REGION" between red and blue rectangles.

Each rectangle is defined by its four corner coordinates. The resulted unit of the overlapped area is unit square.

I could not imagine how can I do it?

Any creative comments would be appreciated.


Solution

  • This type of intersection is easily done by the "min of the maxes" and "max of the mins" idea. To write it out one needs a specific notion for the rectangle, and, just to make things clear I'll use a namedtuple:

    from collections import namedtuple
    Rectangle = namedtuple('Rectangle', 'xmin ymin xmax ymax')
    
    ra = Rectangle(3., 3., 5., 5.)
    rb = Rectangle(1., 1., 4., 3.5)
    # intersection here is (3, 3, 4, 3.5), or an area of 1*.5=.5
    
    def area(a, b):  # returns None if rectangles don't intersect
        dx = min(a.xmax, b.xmax) - max(a.xmin, b.xmin)
        dy = min(a.ymax, b.ymax) - max(a.ymin, b.ymin)
        if (dx>=0) and (dy>=0):
            return dx*dy
    
    print area(ra, rb)
    #  0.5 
    

    If you don't like the namedtuple notation, you could just use:

    dx = max(a[0], b[0]) - min(a[2], b[2])
    

    etc, or whatever notation you prefer.