[英]How to combine bounding boxes in OpenCV (Python)
您將通過分組矩形到 go 並使用源矩形檢查它們,如果它們相交而任何更改(請參閱flag
),則重寫它們的邊界:
def get_intersection_area(box_a, box_b):
x_a = max(box_a[0], box_b[0])
y_a = max(box_a[1], box_b[1])
x_b = min(box_a[2], box_b[2])
y_b = min(box_a[3], box_b[3])
return max(0, x_b - x_a) * max(0, y_b - y_a)
groupped = cv2.groupRectangles(rect, 1, 0.5)[0]
groupped = [(x, y, x+w, y+h) for x, y, w, h in groupped]
rect = [(x, y, x+w, y+h) for x, y, w, h in rect]
flag = True
while flag:
flag = False
for i in range(len(groupped)):
for r in rect:
if 0 < get_intersection_area(groupped[i], r) <\
(r[2]-r[0])*(r[3]-r[1]):
groupped[i] = (
min(groupped[i][0], r[0]), min(groupped[i][1], r[1]),
max(groupped[i][2], r[2]), max(groupped[i][3], r[3]),)
flag = True
(我已經將盒子從 tlwh 格式轉換為 tlrb,因為它對我來說更方便)
這是它現在給出的:
要保留不相交的矩形,請不要使用cv2.groupRectangles()
只說groupped = np.copy(rect)
,盡管它可能會以這種方式做額外的工作並且需要一些優化。
一種簡單的方法是繪制所有填充在遮罩上的矩形。 然后對該蒙版執行 findContours 以找到組合的形狀。 要使結果成為正方形,您可以使用 boundingRect 來查找 x、y、寬度和高度。 請注意,這完全結合了所有矩形,而不僅僅是重疊部分。
您可以在此處找到用於組合矩形示例的示例代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.