【问题标题】:How to combine overlapping rectangles in Python如何在 Python 中组合重叠的矩形
【发布时间】:2016-03-19 04:17:35
【问题描述】:

我在图像上绘制了各种重叠​​的矩形,如下所示:

我想合并这些矩形,以便只选取最外面的矩形。例如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 提供了两个矩形与&amp; 的交集。但是,我无法在 python 中执行此操作。当我调用area 方法时,我得到一个错误(如上面的sn-p 所示)。

问题

如何合并矩形,以便当矩形重叠时,只取最外面的矩形。我想通过使用 OpenCVs 提供的矩形相交&amp; 功能在 python 中解决它。如本文档http://docs.opencv.org/3.1.0/d2/d44/classcv_1_1Rect__.html#gsc.tab=0 中所述,并且在上面发布的链接答案中也提到过。

【问题讨论】:

  • 如果你这样做cv.fromarray(rect).area() 会怎样?
  • @Boud AttributeError: module 'cv2' has no attribute 'fromarray'
  • @Boud 我的代码中没有cv。我尝试做np.fromarray,但得到错误module 'numpy' has no attribute 'fromarray'。由于我没有任何定义为cv,所以当我执行cv.fromarray 时,我会收到错误name 'cv' is not defined。我已经用我的导入更新了问题
  • 我的意思是 cv2.fromarray
  • 是的,这是我的第一条评论。我收到AttributeError: module 'cv2' has no attribute 'fromarray' 的错误

标签: python python-3.x opencv opencv3.0 rect


【解决方案1】:

这可以工作:

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)

我遍历所有矩形并从复制的列表中删除其他矩形中的矩形。

这样做非常效率低下且丑陋,但它应该可以工作(如果我猜对了你的坐标系的话)。

注意:

这只会删除在另一个内部但不部分重叠的矩形

【讨论】:

猜你喜欢
  • 2016-10-17
  • 2016-06-27
  • 2015-06-13
  • 1970-01-01
  • 2015-12-22
  • 2018-11-02
  • 1970-01-01
  • 2023-04-01
  • 2021-06-26
相关资源
最近更新 更多