消除OpenCV中轮廓的重叠边界框

时间:2019-12-13 05:35:54

标签: python opencv opencv-contour

如果两个轮廓在一定公差范围内,我正在处理轮廓并创建斑点,但是我看到的问题是这些轮廓的重叠,我怎么能只有一个边界框而不重叠呢?这是我的代码:

def get_contour_info(contour):
    contour_info = {}
    contour_info['x'], contour_info['y'], contour_info['w'], contour_info['h'] = cv2.boundingRect(contour)
    contour_info['cx'] = contour_info['x'] + contour_info['w'] / 2 
    contour_info['cy'] = contour_info['y'] + contour_info['h'] / 2 
    return contour_info

def process_contour(frame, contours):
    targets = []
    for c in contours:
        target_info = get_contour_info(c)
        target_info['cnt'] = c
        targets.append(target_info)

    full_targets = []
    for i, b in enumerate(targets[:]):
        matched = False
        for i2, b2 in enumerate(targets[i+1:]):
            if abs(b['cx'] - b2['cx']) < 50 and abs(b['cy'] - b2['cy']) < 50 :
                matched = True
                new_blob = np.concatenate([b['cnt'], b2['cnt']])
                hull = cv2.convexHull(new_blob)
                new_blob = cv2.approxPolyDP(hull, 0.01*cv2.arcLength(hull, True), True)
                target_info = get_contour_info(new_blob)
                target_info['cnt'] = new_blob
                full_targets.append(target_info)
                targets.remove(targets[i])              
                break
        if not matched:
            full_targets.append(b)  

    contours = []    
    for g in full_targets:
        x, y, w, h = cv2.boundingRect(g['cnt']) 
        cv2.rectangle(frame, (x,y), (x+w,y+h), (0,0,255), 2)
        cv2.drawContours(frame, [g['cnt']], -1, (0,0,0), 1, lineType=8)
        contours.append(g['cnt'])

在Main函数中,这里进行了一些图像处理,之后我从final_frame获取轮廓

if __name__ == '__main__':
    ....
    ....    
    contours,hierarchy = cv2.findContours(final_frame, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    process_contour(final_frame, contours)

结果如下图所示:

problem_image

如何摆脱重叠的矩形?并创建一个单独的边界矩形,或者创建两个,三个,四个彼此不碰撞的边界框?

从技术上讲,这就是我要实现的目标:

1)我阅读了轮廓并将其放在列表中,并继续向列表中添加新轮廓

2)比较c1和c2,看看它们是否在一定的公差范围内,如果是,那么我将它们组合,并从列表中删除c1并将新的blob添加到final_targets,如果不是,那么我只需将c1添加到final_targets

但是看来,我实际上在某个地方重复了添加项,这就是它们重叠的原因。 感谢响应。

0 个答案:

没有答案