我有一个矩形的坐标x1
,y1
,x2
,y2
以及其他矩形的其他坐标列表。
我想比较我已经拥有的那个与其他人的价值,看看它们是否重叠超过原始矩形的50%
。
我检查了其他资源,但我仍然可以理解它:
答案 0 :(得分:1)
让我们首先将您的问题简化为单一维度:
您有一个间隔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
。