Home > Software design >  How to convert two contours of horizontal line as bbox in a image to get a rectangle?
How to convert two contours of horizontal line as bbox in a image to get a rectangle?

Time:02-04

Lets' say I have two countours,

c = (array([[[   1,  342]],
 
        [[   1,  347]],
 
        [[1705,  347]],
 
        [[1705,  342]]], dtype=int32),
 array([[[ 106,  468]],
 
        [[ 106,  472]],
 
        [[ 107,  473]],
 
        [[1703,  473]],
 
        [[1703,  468]]], dtype=int32))

I am fetching bounding rectangle from contours,

x1,y1,w1,h1 = cv2.boundingRect(c[0])
x2,y2,w2,h2 = cv2.boundingRect(c[1])

# print(x1, y1, w1, h1)
# (1, 342, 1705, 6)
# print(x2, y2, w2, h2)
# (106, 468, 1598, 6)

Basically the (1, 342, 1705, 6) is a bounding box around a horizontal line in a image, and (106, 468, 1598, 6) is a bounding box of another horizontal line in a image.

enter image description here

I want to get the area between these two horizontal line bbox and make it as a rectangle bounding box?

I'd appreciate any help

CodePudding user response:

there's a simple solution: concatenate the contours to a single one, then get the bounding box again (this will also fix the missing left part of the 2nd contour):

d = np.concatenate((c[0],c[1]))
x3,y3,w3,h3 = cv2.boundingRect(d)
print(x3,y3,w3,h3,d)

(1, 342, 1705, 132, array([[[   1,  342]],
       [[   1,  347]],
       [[1705,  347]],
       [[1705,  342]],
       [[ 106,  468]],
       [[ 106,  472]],
       [[ 107,  473]],
       [[1703,  473]],
       [[1703,  468]]], dtype=int32)

if you really wanted the space between the boxes (not including them), you'll have to offset it like:

y3  = h1
h3 -= (h1 h2)
  •  Tags:  
  • Related