【问题标题】:Finding the union of multiple overlapping rectangles - OpenCV python查找多个重叠矩形的并集 - OpenCV python
【发布时间】:2020-07-03 05:38:32
【问题描述】:

我有几个包含单个对象的重叠边界框,但是它们在某些地方重叠最少。作为一个整体,它们包含整个对象,但 openCV 的 groupRectangles 函数不会返回包含对象的框。我拥有的边界框显示为蓝色,我想返回的边界框在这里显示为红色

我想仅获得重叠矩形的并集,但不确定如何在不组合每个矩形的情况下遍历列表。 我有如下所示的 union 和 intersect 函数,以及由 (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")

这会到达那里的大部分路,如下所示

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

【问题讨论】:

  • boxes 只是一个 numpy 数组吗? print(type(boxes))
  • @Zindarod,我之前尝试过使用它,但不幸的是它给出了类似于 groupRectangles 的结果,因为它返回一个小的“平均”边界框,它没有覆盖我的整个对象跨度>
  • @salparadise boxes 是包含 x y w h 信息的数组数组,格式为 [[x1 y1 w1 h1],[x2 y2 w2 h2],...]

标签: python opencv union


【解决方案1】:

我没有使用过 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:])

一切都是一样的。

【讨论】:

  • 我不熟悉itertools.combinations() 函数,但它实际上看起来比我实际做的要好得多。我会尝试实现它,因为它看起来更整洁/更快。
  • @mechaddict 在再次查看您的问题后添加了 zip。
【解决方案2】:

谢谢你,salparadise (https://stackoverflow.com/users/62138/salparadise)。非常有助于找到出路。

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

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

    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

【讨论】:

    【解决方案3】:

    这很糟糕,但经过一番摸索后,我确实设法得到了我想要的结果

    我在下面添加了我的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")
    

    【讨论】:

      【解决方案4】:

      我遇到了类似的情况,将在我的 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
      
      

      【讨论】:

        【解决方案5】:

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

        tImageZone = namedtuple('tImageZone', 'x y w h')
        
        def merge_zone(z1, z2):
            if (z1.x == z2.x and z1.y == z2.y and z1.w == z2.w and z1.h == z2.h):
                return z1
            x = min(z1.x, z2.x)
            y = min(z1.y, z2.y)
            w = max(z1.x + z1.w, z2.x + z2.w) - x
            h = max(z1.y + z1.h, z2.y + z2.h) - y
            return tImageZone(x, y, w, h)
        
        def is_zone_overlap(z1, z2):
            # If one rectangle is on left side of other
            if (z1.x > z2.x + z2.w or z1.x + z1.w < z2.x):
                return False
            # If one rectangle is above other
            if (z1.y > z2.y + z2.h or z1.y + z1.h < z2.y):
                return False
            return True
        
        
        def combine_zones(zones):
            index = 0
            if zones is None: return zones
            while index < len(zones):
                no_Over_Lap = False
                while no_Over_Lap == False and len(zones) > 1 and index < len(zones):
                    zone1 = zones[index]
                    tmpZones = np.delete(zones, index, 0)
                    tmpZones = [tImageZone(*a) for a in tmpZones]
                    for i in range(0, len(tmpZones)):
                        zone2 = tmpZones[i]
                        if (is_zone_overlap(zone1, zone2)):
                            tmpZones[i] = merge_zone(zone1, zone2)
                            zones = tmpZones
                            no_Over_Lap = False
                            break
                        no_Over_Lap = True
                index += 1
            return zones
        

        【讨论】:

          猜你喜欢
          • 2016-12-27
          • 2015-06-13
          • 1970-01-01
          • 2012-06-21
          • 2016-06-27
          • 1970-01-01
          • 1970-01-01
          • 2016-10-17
          • 2018-09-29
          相关资源
          最近更新 更多