Python:并集上的交集

问题描述 投票:0回答:4

我有以下问题。我尝试计算并集的交集,即两个分量的重叠除以两个分量的并集。假设组件 1 是一个矩阵,其中第一个对象所在的位置,组件 2 是一个矩阵,其中第二个对象所在的位置。我可以用

np.logical_and(component == 1, component2 == 1)
来计算重叠。但我如何计算联盟呢?我只对相连的物体感兴趣。

import numpy as np
component1 = np.array([[0,1,1],[0,1,1],[0,1,1]])
component2 = np.array([[1,1,0],[1,1,0],[1,1,0]])
overlap = np.logical_and(component == 1, component2 == 1)
union = ?
IOU = len(overlap)/len(union)
python numpy scipy
4个回答
13
投票

如果您只处理

0
1
,那么使用布尔数组会更容易:

import numpy as np
component1 = np.array([[0,1,1],[0,1,1],[0,1,1]], dtype=bool)
component2 = np.array([[1,1,0],[1,1,0],[1,1,0]], dtype=bool)

overlap = component1*component2 # Logical AND
union = component1 + component2 # Logical OR

IOU = overlap.sum()/float(union.sum()) # Treats "True" as 1,
                                       # sums number of Trues
                                       # in overlap and union
                                       # and divides

>>> 1*overlap
array([[0, 1, 0],
       [0, 1, 0],
       [0, 1, 0]])
>>> 1*union
array([[1, 1, 1],
       [1, 1, 1],
       [1, 1, 1]])
>>> IOU
0.3333333333333333

1
投票

Oleksiimedium 中为您的问题提供了答案。

简单来说:

intersection = numpy.logical_and(result1, result2)

union = numpy.logical_or(result1, result2)

iou_score = numpy.sum(intersection) / numpy.sum(union)

print(‘IoU is %s’ % iou_score)

此外,他对此也给出了很好的解释。看看上面的链接。


1
投票

只需使用专用的 numpy 函数

intersect1d
union1d
:

intersection = np.intersect1d(a, b)
union = np.union1d(a, b)
iou = intersection.shape[0] / union.shape[0]

0
投票

这么多变体 - 我将添加另一个:

  import numpy as np

  SMOOTH = 1e-6

  def iou_numpy(outputs: np.array, labels: np.array):
      outputs = outputs.squeeze(1)

      intersection = (outputs & labels).sum((1, 2))
      union = (outputs | labels).sum((1, 2))

      iou = (intersection + SMOOTH) / (union + SMOOTH)

      thresholded = np.ceil(np.clip(20 * (iou - 0.7), 0, 10)) / 10

      return thresholded  # Or thresholded.mean()

我在这里得到了这段代码 - 我真的很喜欢这个页面如何解释 IoU 指标的概念。

© www.soinside.com 2019 - 2024. All rights reserved.