Python:联合的交集

Liw*_*yen 2 python numpy scipy

我有以下问题。我尝试计算“相交”,即两个分量的重叠除以两个分量的单位。假设component1是第一个对象位于其中的矩阵,component2是第二个对象位于其中的矩阵。我可以用来计算重叠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)
Run Code Online (Sandbox Code Playgroud)

dro*_*oze 5

如果只处理0and 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
Run Code Online (Sandbox Code Playgroud)

  • 我会在这里使用np.count_nonzero而不是sum,因为它更快 (2认同)