Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

so taking on @sturkmen 's idea, we can use groupRectangles() . to make sure, we retain "single" boxes, we have to duplicate them, so even a single box lands in a cluster of it's own ;)

here's an example:

# just for visualization:
def draw(rects,color):
 for r in rects:
  p1 = (r[0], r[1])
  p2 = (r[0]+r[2], r[1]+r[3])
  cv2.rectangle(ocv, p1,p2, color,2)

# draw image
ocv = np.ones((400,400,3),np.uint8) * 127
# demo array of 3 rects (the 1st 2 overlap):
rects = [[20,20,120,130], [40,40,140,100], [150,150,100,100]]
draw(rects,(0,200,0))

# duplicate all of them ;)
l = len(rects)
for r in range(l):
  rects.append(rects[r])
# min cluster size = 2, min distance = 0.5:    
rects,weights = cv2.groupRectangles(rects, 1, .5)
draw(rects, (200,0,0))

print(rects)
print(weights)

[[ 30  30 130 115]
 [150 150 100 100]]
[[4]
 [2]]

so taking on @sturkmen 's idea, we can use groupRectangles() .

to make sure, we retain "single" boxes, we have to duplicate them, so even a single box lands in a cluster of it's own ;)

here's an example:

# just for visualization:
def draw(rects,color):
 for r in rects:
  p1 = (r[0], r[1])
  p2 = (r[0]+r[2], r[1]+r[3])
  cv2.rectangle(ocv, p1,p2, color,2)

# draw image
ocv = np.ones((400,400,3),np.uint8) * 127
 # demo array of 3 rects (the 1st 2 overlap):
overlap and should be merged):
rects = [[20,20,120,130], [40,40,140,100], [150,150,100,100]]
draw(rects,(0,200,0))

# duplicate all of them ;)
l = len(rects)
for r in range(l):
  rects.append(rects[r])
 # min cluster size = 2, min distance = 0.5:    
rects,weights = cv2.groupRectangles(rects, 1, .5)
draw(rects, (200,0,0))

print(rects)
print(weights)

[[ 30  30 130 115]
 [150 150 100 100]]
[[4]
 [2]]