Home/ Reference/ Units & Conversion

RectIntersect: computing intersection area

Overlap of two rectangles: max(0, min(x1+w1, x2+w2) - max(x1, x2)) * max(0, min(y1+h1, y2+h2) - max(y1, y2)). The standard formulation.

Name

RectIntersect: computing intersection area

Notes

Overlap of two rectangles: max(0, min(x1+w1, x2+w2) - max(x1, x2)) * max(0, min(y1+h1, y2+h2) - max(y1, y2)). The standard formulation.

Python example (runnable)

Requires pywin32. The example assumes app / doc / page / layer are already connected. See Connection & Init
Python
def overlap_ratio(a, b):
    """
    Overlap ratio of two bounding boxes
    a, b : any two shape objects
    returns : overlap area / the smaller area (1.0 means they coincide)
    """
    ax, ay, aw, ah = a.GetBoundingBox()
    bx, by, bw, bh = b.GetBoundingBox()

    # the two corners of the overlap
    ix = min(ax + aw, bx + bw) - max(ax, bx)
    iy = min(ay + ah, by + bh) - max(ay, by)

    if ix <= 0 or iy <= 0:              # no overlap at all
        return 0.0

    inter = ix * iy
    smaller = min(aw * ah, bw * bh)
    return inter / smaller if smaller > 0 else 0.0

s1 = app.ActiveSelectionRange(1)
s2 = doc.ActivePage.Shapes.Item(2)
print("Overlap ratio: ", round(overlap_ratio(s1, s2), 3))

About this section: Units & Conversion

Units & Conversion — document units and conversion.

Other entries in this section