首页 > 解决方案 > OpenCV 上的 groupRectangles 未按预期执行

问题描述

所以我正在尝试使用 OpenCV 自动从图形中检测轴标签。现在,我的程序检测标签相对较好,并输出一个矩形列表,但是一个轴标签值通常被分成许多矩形。我想将这些组合在一起,我听说 cv2.groupRectangles() 可以完成它。

到目前为止,我可以检测到以下框:

array([[[ 76, 620, 107, 635]],
       [[ 87, 540,  96, 554]],
       [[ 77, 459, 100, 473]],
       [[ 77, 377, 107, 392]],
       [[ 77, 297, 100, 311]],
       [[ 68, 217, 101, 231]],
       [[ 86, 139,  94, 147]],
       [[ 68, 135, 107, 150]],
       [[ 69,  54, 107,  69]],
       [[ 77,  54,  97,  69]],
       [[545, 641, 580, 655]],
       [[454, 640, 489, 655]],
       [[364, 641, 399, 655]],
       [[375, 641, 399, 655]],
       [[364, 640, 373, 654]],
       [[636, 638, 671, 655]],
       [[647, 641, 671, 655]],
       [[660, 643, 667, 651]],
       [[273, 638, 309, 655]],
       [[273, 641, 284, 655]],
       [[284, 640, 309, 655]],
       [[183, 638, 214, 655]],
       [[183, 641, 196, 655]],
       [[105, 637, 115, 655]],
       [[ 77, 625, 102, 634]]])

如图所示:带有所有框的图

我使用 groupRectangles 如下:

def groupRect(rectarray, rectthreshold=1, eps=0.1):
    """
    Groups similar rectangles together in rectangle array \n
    Input : Rectangle Array \n
    Output : Rectangle Array without split parts
    """
    results = cv.groupRectangles(np.concatenate((rectarray, rectarray)),1,eps=eps)[0]
    results = [[group] for group in results]
    return np.array(results)

我重复 rectarray 以便算法保留不与任何其他矩形重叠的任何矩形。但是,从下面的结果图中可以看出,存在一些问题:

1)它摆脱了0.01左右的矩形

2)它没有摆脱 125 处的矩形,其中一个完全被另一个包围

如果有人能帮助我理解为什么 groupRectangles 代码会给出这个输出,或者建议另一种算法来做到这一点,我将非常感激。

另外,是否可以取重叠矩形的最大封闭区域而不是取两个矩形的平均值?

无框图

使用 groupRectangles 后带框的图形

标签: opencvrectangles

解决方案


I modified the eps parameter to 0.05.

results = cv2.groupRectangles(np.concatenate((rect_old, rect_old)),1,eps=0.05)[0]
img2 = img.copy()
for r in results:
    cv2.rectangle(img2,(r[0], r[1]),(r[2], r[3]),(255,0,0),1)

enter image description here

EDIT

Here is some info on the parameters take more this page:

Parameters:

  • rectList – Input/output vector of rectangles. Output vector includes retained and grouped rectangles. (The Python list is not modified in place.)

  • groupThreshold – Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it.

  • eps – Relative difference between sides of the rectangles to merge them into a group.


推荐阅读