opencv python中查找矩形交集的意外结果

问题描述 投票:0回答:1

希望你今天一切顺利。我试图在 opencv 中找到两个矩形的交集,但结果不是我期望看到的。简而言之:

In:
intersect = obj_1 & obj_2
print('intersect: ', intersect, '; obj_1: ', obj_1, '; obj_2: ', obj_2)

Out:
intersect: [219  11  37  21];
obj_1: [1 1 1 1];
obj_2: [219  11  37  21]

在这种情况下,“相交”不应该显示类似 [0 0 0 0] 的内容吗?

python opencv intersection rectangles
1个回答
-1
投票

我希望用简单快速的方法解决这个问题,但我猜问题是数据类型。它是一种 np 数组,不适用于 opencv &。所以,我使用了这种方法并且它有效:https://ru.stackoverflow.com/questions/758529

该方法使用两个轮廓的2个点:左下角和右上角,坐标的起点是左下角。

在我们的例子中,坐标从左上角开始,解决方案有点不同。这是我做的:

obj_1[0:4] = [x, y, width, height]
obj_2[0:4] = [x, y, width, height]
                
x1=int(obj_1[0])
y1=int(obj_1[1])
x2=int(obj_1[0]) + int(obj_1[2])
y2=int(obj_1[1]) + int(obj_1[3])
x3=int(obj_2[0])
y3=int(obj_2[1])
x4=int(obj_2[0]) + int(obj_2[2])
y4=int(obj_2[1]) + int(obj_2[3])
                
left = max(x1, x3)
bottom = max(y1, y3)
right = min(x2, x4)
top = min(y2, y4)

width = right - left
height = bottom - top

#Below zero variables will brake the formula, zero should be minimal:
if width < 0: width = 0 
if height < 0: height = 0

#Here we have the intersection area size in pixels (if 0 so there are no intersection):
intersect = width * height
© www.soinside.com 2019 - 2024. All rights reserved.