Python 去除OpenCV中轮廓的重叠边界框
我正在处理轮廓并创建一个blob,如果两个轮廓在一定的公差范围内,但我看到的问题是这些轮廓的重叠,我怎么能只有一个边界框而不重叠它?这是我的密码:Python 去除OpenCV中轮廓的重叠边界框,python,opencv,opencv-contour,Python,Opencv,Opencv Contour,我正在处理轮廓并创建一个blob,如果两个轮廓在一定的公差范围内,但我看到的问题是这些轮廓的重叠,我怎么能只有一个边界框而不重叠它?这是我的密码: def get_contour_info(contour): contour_info = {} contour_info['x'], contour_info['y'], contour_info['w'], contour_info['h'] = cv2.boundingRect(contour) contour_info
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'])
此结果如下图所示:
我怎样才能去掉重叠的矩形?创建一个单一的边界矩形,或者两个、三个、四个不会相互碰撞的边界框
从技术上讲,这就是我想要实现的:
1) 我读了轮廓,把它放在一个列表中,并不断地向列表中添加新的轮廓
2) 比较c1和c2,看看它们是否在一定的公差范围内,如果是,那么我将它们合并,从列表中删除c1并将新blob添加到最终的_目标中,如果不是,那么我只需将c1添加到最终的_目标中
但看起来,在某个地方,我实际上是在复制加法,这就是它们重叠的原因。
感谢您的回复 你看了吗?谢谢你的回复,但它不适用,因为它正在寻找轮廓继承人级别(这类问题非常常见),以消除图像的重叠问题,但在我的情况下,我们已经过了那个阶段。你看了吗?谢谢你的回复,但它不适用,因为它正在寻找轮廓继承人级别(这类问题非常常见)以消除图像的重叠问题,但就我而言,我们已经过了那个阶段。
if __name__ == '__main__':
....
....
contours,hierarchy = cv2.findContours(final_frame, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
process_contour(final_frame, contours)