python - 如何在 Python 中组合重叠的矩形

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

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

enter image description here

我想合并这些矩形,以便只使用最外面的矩形。例如,一个矩形用于 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)

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

这样做极其低效且丑陋,但它应该可以工作(如果我猜对了您的坐标系)。

注意:

这只会移除位于另一个矩形内但不部分重叠的矩形

关于python - 如何在 Python 中组合重叠的矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36097761/

相关文章:

linux - 在 Linux 环境中使用 XlsxWriter

python - 如果 collections.defaultdict 不可用怎么办?

python - 如何在 Tkinter 中检测圆圈的某种颜色?

python - 根据列表的内容从数据框中选择列

c++ - 我有 3 个错误 :expected a ")" , 需要一个表达式,long 类型的参数与 U32 类型的参数不兼容

c++ - opencv函数cvcvtcolor和cvtcolor有什么区别

python - 如何检测检测到的形状OpenCV的颜色

python - 如何让闪烁的字符串也改变值? ( python 3.5)

python-3.x - Python 中文本 block 开头的全部大写的正则表达式

python - '\t' 在 python 正则表达式对象中匹配什么?