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 & InitPython
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.
- This section has 8 entries; this is one of them.
- See the full section index: Units & Conversion
Other entries in this section
- doc.UnitThe current document unit (cdrUnit enum). Every geometry API follows i
- doc.Unit = cdrMillimeterSwitch to millimetres and you can write millimetres directly instead o
- Font size: points vs document unitsThe one measurement that ignores doc.Unit: the size argument of Create
- 1 inch = 25.4 mm = 72 pt = 96 pxThe conversion basis. 1490/25.4 in the code converts 1490 mm to inches
- page.SizeWidth * page.SizeHeightPage area in square units. Use it as the denominator when you ask what
- shape.GetBoundingBox() → w*hBounding box area, for overlap tests like "are these two G's the same
- shape.Curve.Area / shape.Curve.LengthTrue area and perimeter. Curve objects only.