【问题标题】:How could I match two detected rectangles from image?如何匹配图像中检测到的两个矩形?
【发布时间】:2021-02-26 03:46:48
【问题描述】:

我想计算两个基于深度学习的检测器从许多图像中检测到的矩形的比率。例如下图,首先,第一个检测器检测到大圆(c1 和 c2),第二个检测器检测到小圆(d1 和 d2)。 现在,第一个检测器返回 c1 和 c2 的坐标,第二个检测器也返回 d1 和 d2 的坐标。

所以我想做一个可以自动计算比率d1/c1和d2/c2的函数和代码。所以,我的想法是,如果小坐标(例如d1,d2)包含在相应的大坐标(例如c1,c2)中,则它们匹配用于计算比率。

c1 坐标 (xmin, ymin, xmax, ymax) : (10, 10, 30, 30) d1 坐标 : (13, 15, 20, 23)

c2 坐标:(20, 20, 40, 40) d2坐标:(25, 24, 32, 33)

但是,我不知道 OpenCV 和 python 的很多功能。 你能做一些代码、函数或推荐库吗?

谢谢

【问题讨论】:

  • “你能不能做一些代码”是让你的问题被否决和关闭的可靠方法。如果您已经有返回坐标的检测器,那么编写您描述的函数听起来相当琐碎(至少以低效的方式)并且不需要库。请分享您的代码并提出问题,了解您的确切位置。
  • 如您所知,基于深度学习的目标检测代码非常长。很难发布所有内容。所以我简要解释一下面临的问题。
  • 我明白了,但是如果我没记错的话,你的问题不涉及深度学习部分,它是关于一些后处理的,你需要的是一个返回的函数f(coordintaes_of_detected_objects)比率。我要求的是,如果可能的话,你分享你已经为这个功能所做的事情。你的想法听起来不错,所以我很好奇你为什么没有实现它的蛮力版本。也许我错过了一些微不足道的事情,在这种情况下我道歉。
  • 感谢您的评论。我找到了这个问题和答案(stackoverflow.com/questions/40622016/…)。我希望它对面临类似问题的其他人有用。

标签: python opencv computer-vision


【解决方案1】:

此任务通常使用的度量标准是“Intersection over Union”,即 IOU。

使用[50, 60, 200, 150]这种格式的边界框(矩形)输入,您可以像这样为其编写自定义函数-

def intersection_over_union(box1, box2):
    # Get coordinates of the intersection 
    x1 = max(box1[0], box2[0])
    y1 = max(box1[1], box2[1])
    x2 = min(box1[2], box2[2])
    y2 = min(box1[3], box2[3])

    # Get the area of intersection rectangle
    intersection = max(0, x2 - x1 + 1) * max(0, y2 - y1 + 1)

    # Get the area of both rectangles
    box1Area = (box1[2] - box1[0] + 1) * (box1[3] - box1[1] + 1)
    box2Area = (box2[2] - box2[0] + 1) * (box2[3] - box2[1] + 1)

    iou = intersection / float(box1Area + box2Area - intersection)

    return iou

请注意,这需要在以下条件正确的情况下以标准格式返回边界框:

assert box1['x1'] <= box1['x2']
assert box1['y1'] <= box1['y2']
assert box2['x1'] <= box2['x2']
assert box2['y1'] <= box2['y2']

更多详情请看answer。

如果边界框对不满足该条件,最好使用 sklearn 中的 jaccard_score(IOU 的另一个名称)

from sklearn.metrics import jaccard_score
import numpy as np

box1 = [180, 400, 450, 450]
box2 = [200, 450, 425, 425]

img = np.zeros((800, 800, 3), np.uint8)  # use your image shape here or directly below

img1 = cv2.rectangle(np.zeros(img.shape), (box1[0], box1[1]), (box1[2], box1[3]), (1, 1, 1), -1) 
img2 = cv2.rectangle(np.zeros(img.shape), (box2[0], box2[1]), (box2[2], box2[3]), (1, 1, 1), -1)

jaccard_score(img1.ravel(),img2.ravel())

【讨论】:

    猜你喜欢
    • 2020-04-21
    • 2019-08-05
    • 2014-04-30
    • 2016-09-19
    • 2011-08-22
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 2018-01-27
    相关资源
    最近更新 更多