如何将图像中的水平线的两条轮廓转换为bbox以获得矩形?

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

假设我有两个国家,

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

我正在从轮廓中获取边界矩形,

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)

基本上 (1, 342, 1705, 6) 是图像中水平线周围的边界框,并且 (106, 468, 1598, 6) 是图像中另一条水平线的边界框。

我想获取这两条水平线bbox之间的区域并将其作为矩形边界框?

如有任何帮助,我将不胜感激

有一个简单的解决方案:将轮廓连接成一个轮廓,然后再次获取边界框(这也将修复第二个轮廓左侧缺失的部分):

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)

如果你真的想要 space 框之间(不包括它们),你必须像这样偏移它:

y3 += h1
h3 -= (h1+h2)