mec*_*ict 9 python union opencv
我有几个重叠的边界框,它们包含一个对象,但是它们在某些地方的重叠最小。作为一个整体,它们包含整个对象,但 openCV 的 groupRectangles 函数不返回包含对象的框。我的边界框显示为蓝色,我想返回的边界框显示为红色

我只想获得重叠矩形的联合,但不确定如何在不组合每个矩形的情况下遍历列表。我有如下所示的 union 和 intersect 函数,以及由 (xywh) 表示的矩形列表,其中 x 和 y 是框左上角的坐标。
def union(a,b):
x = min(a[0], b[0])
y = min(a[1], b[1])
w = max(a[0]+a[2], b[0]+b[2]) - x
h = max(a[1]+a[3], b[1]+b[3]) - y
return (x, y, w, h)
def intersection(a,b):
x = max(a[0], b[0])
y = max(a[1], b[1])
w = min(a[0]+a[2], b[0]+b[2]) - x
h = min(a[1]+a[3], b[1]+b[3]) - y
if w<0 or h<0: return () # or (0,0,0,0) ?
return (x, y, w, h)
Run Code Online (Sandbox Code Playgroud)
我的组合功能目前如下:
def combine_boxes(boxes):
noIntersect = False
while noIntersect == False and len(boxes) > 1:
a = boxes[0]
print a
listBoxes = boxes[1:]
print listBoxes
index = 0
for b in listBoxes:
if intersection(a, b):
newBox = union(a,b)
listBoxes[index] = newBox
boxes = listBoxes
noIntersect = False
index = index + 1
break
noIntersect = True
index = index + 1
print boxes
return boxes.astype("int")
Run Code Online (Sandbox Code Playgroud)
这得到了大部分的方式,如下所示

还有一些嵌套的边界框我不确定如何继续迭代。
我没有使用过 openCV,所以该对象可能需要更多的修改,但也许使用 itertools.combinations 来使函数combine_boxes更简单:
import itertools
import numpy as np
def combine_boxes(boxes):
new_array = []
for boxa, boxb in itertools.combinations(boxes, 2):
if intersection(boxa, boxb):
new_array.append(union(boxa, boxb))
else:
new_array.append(boxa)
return np.array(new_array).astype('int')
Run Code Online (Sandbox Code Playgroud)
编辑(你可能实际上需要zip)
for boxa, boxb in zip(boxes, boxes[1:])
Run Code Online (Sandbox Code Playgroud)
一切都一样。