OpenCV Python检测矩形内的对象

2024-04-27 04:12:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个代码:

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之间的交叉点,如图中所示:

enter image description here

所以我需要一个布尔变量,如果这两个矩形有一些公共面积,它应该是真的。 我怎么能做到呢?在


Tags: 代码fromimportnumpyimgmatplotlibasnp
1条回答
网友
1楼 · 发布于 2024-04-27 04:12:20

您可以参考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

相关问题 更多 >