[英]Find area of overlapping rectangles in Python / OpenCV with a raw list of points
我有一個矩形的坐標x1
、 y1
、 x2
、 y2
以及其他矩形的其他坐標列表。
我想將我已經擁有的值與其他值進行比較,看看它們是否重疊超過原始矩形的50%
。
我檢查了其他資源,但我仍然可以理解它:
首先讓我們將問題簡化為一個維度:
您有一個區間A = [a0, a1]
並且想找出另一個區間B = [b0, b1]
與之相交多少。 我將用=
表示A
,用-
表示B
有6種可能的情況:
A
包含B
, intersection = b1 - b0
a0 b0 b1 a1 ============== ------
B
包含A
, intersection = a1 - a0
b0 a0 a1 b1 ====== --------------
B
從左側與A
相交, intersection = b1 - a0
b0 a0 b1 a1 ========== ----------
B
從右邊與A
相交, intersection = a1 - b0
a0 b0 a1 b1 ========== ----------
B
在A
的左側, intersection = 0
b0 b1 a0 a1 ====== ------
B
在A
的右邊, intersection = 0
a0 a1 b0 b1 ====== ------
基於此,我們可以定義一個函數,該函數在給定兩個間隔A = [a0, a1]
和B = [b0, b1]
,返回它們相交的數量:
def calculateIntersection(a0, a1, b0, b1):
if a0 >= b0 and a1 <= b1: # Contained
intersection = a1 - a0
elif a0 < b0 and a1 > b1: # Contains
intersection = b1 - b0
elif a0 < b0 and a1 > b0: # Intersects right
intersection = a1 - b0
elif a1 > b1 and a0 < b1: # Intersects left
intersection = b1 - a0
else: # No intersection (either side)
intersection = 0
return intersection
這幾乎就是您需要的一切。 要找出兩個矩形相交的數量,您只需要在X
軸和Y
軸上執行此函數,然后將這些數量相乘即可得出相交的面積:
# The rectangle against which you are going to test the rest and its area:
X0, Y0, X1, Y1, = [0, 0, 10, 10]
AREA = float((X1 - X0) * (Y1 - Y0))
# Rectangles to check
rectangles = [[15, 0, 20, 10], [0, 15, 10, 20], [0, 0, 5, 5], [0, 0, 5, 10], [0, 5, 10, 100], [0, 0, 100, 100]]
# Intersecting rectangles:
intersecting = []
for x0, y0, x1, y1 in rectangles:
width = calculateIntersection(x0, x1, X0, X1)
height = calculateIntersection(y0, y1, Y0, Y1)
area = width * height
percent = area / AREA
if (percent >= 0.5):
intersecting.append([x0, y0, x1, y1])
結果將是:
[15, 0, 20, 10]
在X軸上不相交,因此width = 0
。 [0, 15, 10, 20]
不在Y軸上相交,因此height = 0
。 [0, 0, 5, 5]
僅相交25%
。 [0, 0, 5, 10]
相交50%
並將其添加到intersecting
。 [0, 5, 10, 100]
相交50%
並將其添加到intersecting
。 [0, 0, 100, 100]
相交100%
並將其添加到intersecting
。 重疊面積是重疊寬度和重疊高度的乘積。
要找到矩形XY
和xy
的寬度重疊,請取最右邊的左邊緣和最左邊的右邊緣。 在數值上, max(X1, x1)
和min(X2, x2)
。 因此重疊寬度為min(X2, x2) - max(X1, x1)
。 如果這是負數,則根本沒有重疊。 重復高度。
因此,重疊區域可以用一個公式表示:
max(0, min(X2, x2) - max(X1, x1)) . max(0, min(Y2, y2) - max(Y1, y1))
【總成本:六次比較,兩次減法,一次乘積(加一次與目標區域的比較)。】
作為微優化,您可以立即得出“不”的結論,如果
min(X2, x2) - max(X1, x1) < 50% (X2 - X1)
[有一定的概率,成本降低到三比一減。]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.