找到多个重叠矩形的并集 - OpenCV python

时间:2017-09-17 05:10:21

标签: python opencv union

我有几个重叠的边界框,包含一个对象,但在某些地方它们的重叠程度很低。作为一个整体,它们包含整个对象,但openCV的groupRectangles函数不返回包含该对象的框。我有的边框用蓝色显示,我想要返回的边框在这里用红色显示

我想得到只有重叠矩形的并集,但我不确定如何在不组合每个矩形的情况下迭代列表。 我有下面显示的并集和交叉函数,以及由(x y w h)表示的矩形列表,其中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)

我的合并功能目前如下:

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")

这大部分都在那里,如图所示

还有一些嵌套的边界框,我不确定如何继续迭代。

5 个答案:

答案 0 :(得分:2)

我没有使用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')

编辑(您实际上可能需要zip

for boxa, boxb in zip(boxes, boxes[1:])
一切都是一样的。

答案 1 :(得分:1)

谢谢,萨尔天堂(https://stackoverflow.com/users/62138/salparadise)。寻找出路非常有帮助。

但是该解决方案看起来可以将矩形重复添加到new_array中。例如A B C彼此没有交集,A B C将分别添加两次。因此,new_array将包含A B A C BC。 请参考修改后的代码。希望对您有所帮助。

已经在多个测试用例上对其进行了测试。看起来工作正常。

    def merge_recs(rects):
        while (1):
            found = 0
            for ra, rb in itertools.combinations(rects, 2):
                if intersection(ra, rb):
                    if ra in rects:
                        rects.remove(ra)
                    if rb in rects:
                        rects.remove(rb)
                    rects.append((union(ra, rb)))
                    found = 1
                    break
            if found == 0:
                break

        return rects

答案 2 :(得分:0)

这非常笨拙,但经过一段时间的努力,我确实得到了我想要的结果

我已在下方添加了combine_boxes功能,以防任何人遇到类似问题。

def combine_boxes(boxes):
     noIntersectLoop = False
     noIntersectMain = False
     posIndex = 0
     # keep looping until we have completed a full pass over each rectangle
     # and checked it does not overlap with any other rectangle
     while noIntersectMain == False:
         noIntersectMain = True
         posIndex = 0
         # start with the first rectangle in the list, once the first 
         # rectangle has been unioned with every other rectangle,
         # repeat for the second until done
         while posIndex < len(boxes):
             noIntersectLoop = False
            while noIntersectLoop == False and len(boxes) > 1:
                a = boxes[posIndex]
                listBoxes = np.delete(boxes, posIndex, 0)
                index = 0
                for b in listBoxes:
                    #if there is an intersection, the boxes overlap
                    if intersection(a, b): 
                        newBox = union(a,b)
                        listBoxes[index] = newBox
                        boxes = listBoxes
                        noIntersectLoop = False
                        noIntersectMain = False
                        index = index + 1
                        break
                    noIntersectLoop = True
                    index = index + 1
            posIndex = posIndex + 1

    return boxes.astype("int")

答案 3 :(得分:0)

如果您需要一个最大的框,则投票最多的答案将不起作用,但是上面的框可以起作用,但是有一个错误。 为某人发布正确的代码

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case REQUEST_CHECK_SETTINGS_GPS:
            switch (resultCode) {
                case Activity.RESULT_OK:
                    getMyLocation();
                    break;
                case Activity.RESULT_CANCELED:
                    finish();
                    break;
            }
            break;
    }
}

答案 4 :(得分:0)

我遇到了类似的情况,将在OpenCV项目的每个框架中找到的所有相交的矩形合并在一起,一段时间后,我终于想出了一个解决方案,并希望在这里与共享矩形的头痛人士分享。 (这可能不是最好的解决方案,但是很简单)

import itertools

# my Rectangle = (x1, y1, x2, y2), a bit different from OP's x, y, w, h
def intersection(rectA, rectB): # check if rect A & B intersect
    a, b = rectA, rectB
    startX = max( min(a[0], a[2]), min(b[0], b[2]) )
    startY = max( min(a[1], a[3]), min(b[1], b[3]) )
    endX = min( max(a[0], a[2]), max(b[0], b[2]) )
    endY = min( max(a[1], a[3]), max(b[1], b[3]) )
    if startX < endX and startY < endY:
        return True
    else:
        return False

def combineRect(rectA, rectB): # create bounding box for rect A & B
    a, b = rectA, rectB
    startX = min( a[0], b[0] )
    startY = min( a[1], b[1] )
    endX = max( a[2], b[2] )
    endY = max( a[3], b[3] )
    return (startX, startY, endX, endY)

def checkIntersectAndCombine(rects):
    if rects is None:
        return None
    mainRects = rects
    noIntersect = False
    while noIntersect == False and len(mainRects) > 1:
        mainRects = list(set(mainRects))
        # get the unique list of rect, or the noIntersect will be 
        # always true if there are same rect in mainRects
        newRectsArray = []
        for rectA, rectB in itertools.combinations(mainRects, 2):
            newRect = []
            if intersection(rectA, rectB):
                newRect = combineRect(rectA, rectB)
                newRectsArray.append(newRect)
                noIntersect = False
                # delete the used rect from mainRects
                if rectA in mainRects:
                    mainRects.remove(rectA)
                if rectB in mainRects:
                    mainRects.remove(rectB)
        if len(newRectsArray) == 0:
            # if no newRect is created = no rect in mainRect intersect
            noIntersect = True
        else:
            # loop again the combined rect and those remaining rect in mainRects
            mainRects = mainRects + newRectsArray
    return mainRects