簡體   English   中英

如何在Python中組合重疊矩形

[英]How to combine overlapping rectangles in Python

我在圖像上繪制了各種重疊​​的矩形,如下所示:

在此輸入圖像描述

我想鞏固這些矩形,以便只采取最外面的矩形。 例如,一個用於computer.org/webinars/Agile2矩形和一個用於FREE WEBINAR等的矩形。

我繪制矩形的方式是這樣的:

import cv2
import numpy as np
.....
for rect in rects_new:
    #print (str(type(rect))) #<class 'numpy.ndarray'>
    #print (rect.area()) # gives error that 'numpy.ndarray' object has no attribute 'area'
    cv2.rectangle(vis, (rect[0],rect[1]), (rect[0]+rect[2],rect[1]+rect[3]), (0, 255, 255), 2)

我遇到了這個答案https://stackoverflow.com/a/24061475/44286和這個答案http://answers.opencv.org/question/67091/how-to-find-if-2-rectangles-are-overlapping -each-other /?answer = 67092#post-id-67092 ,表明opencv提供兩個矩形與&交集。 但是,我無法在python中執行此操作。 當我調用area方法時,我收到一個錯誤(如上面的代碼片段所示)。

如何合並矩形,以便在矩形重疊時,僅采用最外面的矩形。 我想通過使用OpenCVs提供的矩形交叉&功能在python中解決它。 如本文檔中所述, http://docs.opencv.org/3.1.0/d2/d44/classcv_1_1Rect__.html#gsc.tab=0 ,並且在上面發布的鏈接答案中也提到了。

這可能有效:

def inOtherRect(rect_inner,rect_outer):
    return rect_inner[0]>=rect_outer[0] and \
        rect_inner[0]+rect_inner[2]<=rect_outer[0]+rect_outer[2] and \
        rect_inner[1]>=rect_outer[1] and \
        rect_inner[1]+rect_inner[3]<=rect_outer[1]+rect_outer[3] and \
        (rect_inner!=rect_outer)

outer_rects=[rects_new[:]]
for rect_inner in rects_new:
    for rect_outer in rects_new:
        if(inOtherRect(rect_inner,rect_outer)):
            if rect_inner in outer_rects:
                outer_rects.remove(rect_inner)


for rect in outer_rects:
    #print (str(type(rect))) #<class 'numpy.ndarray'>
    #print (rect.area()) # gives error that 'numpy.ndarray' object has no attribute 'area'
    cv2.rectangle(vis, (rect[0],rect[1]), (rect[0]+rect[2],rect[1]+rect[3]), (0, 255, 255), 2)

我遍歷所有矩形並從復制列表中刪除其他矩形內的那些矩形。

這樣做是非常 inefficent和丑陋,但它應該工作(如果我猜你的坐標系右)。

注意:

這只會刪除在另一個內部但不是部分重疊的矩形

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM