Python: 交并比

8
我有一个问题。我试图计算交并比(Intersection over Union),它是两个组件的重叠部分除以两个组件的联合部分。假设component1是一个矩阵,其中第一个对象为1;component2是一个矩阵,其中第二个对象为1。我可以通过 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)

您在文章中希望从输入中得到什么样的期望输入? - jpp
你的意思是我的期望输出吗?这将是:IOU = 重叠/并集。 - Liwellyen
抱歉,是的,期望的输出不清楚,不知道你在所有这些之后想要什么。 - jpp
我想要得到重叠点数除以联合点数的分数或数字。有了这个分数,我可以进行后处理计算。 - Liwellyen
3个回答

13

如果你只涉及到 01,那么使用布尔数组会更容易:

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

啊,将数组视为布尔值是诀窍,非常感谢! - Liwellyen
2
我会在这里使用np.count_nonzero而不是sum,因为它更快。 - Mehdi

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函数intersect1dunion1d

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接