【问题标题】:OpenCV - Python - detect object inside a rectangle [duplicate]OpenCV - Python - 检测矩形内的对象[重复]
【发布时间】:2019-01-02 06:53:06
【问题描述】:

我有这个代码:

import cv2
from matplotlib import pyplot as plt
import numpy as np
img = cv2.imread('forklift2.jpg')

A = cv2.rectangle(img, (180, 90), (352, 275), (255,0,0), 2)
B = cv2.rectangle(img, (100, 220), (300, 275), (155,122,100), 2)

cv2.imshow('Object detector', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

我需要检测 2 个矩形 A 和 B 之间的交叉点,如图所示:

所以我需要一个布尔变量,如果 2 个矩形有一些公共区域,则该变量应该为真。 我怎样才能做到这一点?

【问题讨论】:

  • 这里有很多案例需要考虑。两个矩形可以完全不相交吗?它们中的一个可以完全位于另一个内部吗?否则,像if (pt.x > x0_2) and (pt.x < x1_1) and (pt.y > y0_2) and (pt.y < y1_1) 这样的简单逻辑就可以解决问题; xi_j 其中i 是开始和结束坐标索引,j 是矩形索引(类似于yi_j)。
  • 嗨,谢谢,确实有很多情况,我的问题是关于使用库(或 cv2 函数)的可能性
  • Module pygame 有 Rect 类,它有一个函数 clip()。见这里:pygame.org/docs/ref/rect.html#pygame.Rect.clip

标签: python opencv3.0


【解决方案1】:

您可以参考IOU实现如下:

def pre_IOU(Reframe, GTframe):
    """
       input is rect diagonal points 
    """
    x1 = Reframe[0]
    y1 = Reframe[1]
    width1 = Reframe[2] - Reframe[0]
    height1 = Reframe[3] - Reframe[1]

    x2 = GTframe[0]
    y2 = GTframe[1]
    width2 = GTframe[2]-GTframe[0]
    height2 = GTframe[3]-GTframe[1]

    endx = max(x1+width1,x2+width2)
    startx = min(x1,x2)
    width = width1+width2-(endx-startx)

    endy = max(y1+height1,y2+height2)
    starty = min(y1,y2)
    height = height1+height2-(endy-starty)

    if width <=0 or height <= 0:
        ratio = 0
        return 0
    else:
        Area = width*height # two box cross  
        Area1 = width1*height1
        Area2 = width2*height2
        ratio = Area*1./(Area1+Area2-Area)
        return Area

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 2020-07-24
    相关资源
    最近更新 更多