![](/img/trans.png)
[英]Finding the area of intersection of multiple overlapping rectangles in Python
[英]Intersection of overlapping rectangles
我是一名工業工程師,所以你知道我的編碼不是那么好,這就是為什么我需要你的幫助。 我的問題是我需要首先知道兩個矩形之間的相交區域,以便檢查是否發生重疊,這必須對 6 個矩形進行,我需要檢查它們是否重疊。 我的第二個問題是,我在一個大倉庫內有 6 個矩形,並且有明確的邊界,我想最大化利用面積。 我該如何編寫代碼來做到這一點。 我使用了在線的波紋管代碼,但我不知道如何使用它來檢查 6 個矩形。
# Python program to check if rectangles overlap
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
# Returns true if two rectangles(l1, r1)
# and (l2, r2) overlap
def doOverlap(l1, r1, l2, r2):
# If one rectangle is on left side of other
if(l1.x >= r2.x or l2.x >= r1.x):
return False
# If one rectangle is above other
if(l1.y <= r2.y or l2.y <= r1.y):
return False
return True
# Driver Code
if __name__ == "__main__":
l1 = Point(0, 10)
r1 = Point(10, 0)
l2 = Point(5, 5)
r2 = Point(15, 0)
if(doOverlap(l1, r1, l2, r2)):
print("Rectangles Overlap")
else:
print("Rectangles Don't Overlap")
這可能會幫助您入門:
一個Rectangle
在這里定義了一個base_point
(它是左下角的點)和一個size
(它在x
和y
延伸了多少)。
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
@dataclass
class Rectangle:
base_point: Point
size: Point
def x_overlap(self, other: "Rectangle") -> bool:
if self.base_point.x < other.base_point.x:
lower = self
higher = other
else:
lower = other
higher = self
if lower.base_point.x + lower.size.x >= higher.base_point.x:
return True
else:
return False
def y_overlap(self, other: "Rectangle") -> bool:
if self.base_point.y < other.base_point.y:
lower = self
higher = other
else:
lower = other
higher = self
if lower.base_point.y + lower.size.y >= higher.base_point.y:
return True
else:
return False
def overlap(self, other: "Rectangle") -> bool:
return self.x_overlap(other) and self.y_overlap(other)
r0 = Rectangle(base_point=Point(x=0, y=0), size=Point(x=3, y=2))
r1 = Rectangle(base_point=Point(x=2, y=1), size=Point(x=3, y=2))
print(r0.overlap(r1))
如果矩形在 x 軸和 y 軸上重疊,則它們重疊。 代碼可能設計過度……您可能希望簡化它以滿足您的需求。 但它的方式 - 我認為 - 它很好地展示了這個想法。
為了找出是否有更多的矩形重疊,您必須將所有矩形相互比較...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.