Ale*_*xis 2 python opencv coordinates python-3.x cv2
我有一个矩形的坐标x1, y1, x2,y2和其他矩形的其他坐标列表。
我想将我已经拥有的值与其他值进行比较,以查看它们是否比50%原始矩形重叠更多。
我检查了其他资源,但仍然可以理解它:
让我们首先将您的问题简化为单一维度:
你有一个区间A = [a0, a1],想知道另一个区间B = [b0, b1]与它相交多少。我将代表A与=和B用-。
有6种可能的情况:
A包含B,intersection = b1 - b0
a0 b0 b1 a1
==============
------
Run Code Online (Sandbox Code Playgroud)B包含A,intersection = a1 - a0
b0 a0 a1 b1
======
--------------
Run Code Online (Sandbox Code Playgroud)BA从左边相交,intersection = b1 - a0
b0 a0 b1 a1
==========
----------
Run Code Online (Sandbox Code Playgroud)BA从右边相交,intersection = a1 - b0
a0 b0 a1 b1
==========
----------
Run Code Online (Sandbox Code Playgroud)B位于 的左侧A,intersection = 0
b0 b1 a0 a1
======
------
Run Code Online (Sandbox Code Playgroud)B在 的右边A,intersection = 0
a0 a1 b0 b1
======
------
Run Code Online (Sandbox Code Playgroud)基于此,我们可以定义一个函数,在给定两个区间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
Run Code Online (Sandbox Code Playgroud)
这几乎就是你需要的一切。要找出两个矩形相交多少,您只需要在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])
Run Code Online (Sandbox Code Playgroud)
结果将是:
[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.| 归档时间: |
|
| 查看次数: |
4835 次 |
| 最近记录: |