Search code examples
pythonnumpyscipy

Python: Intersection over Union


I have the following question. I try to calculate the Intersection over Union, which is the overlap of two components divided by the unioin of two components. Lets assume component1 is a matrix with ones where the first object is and component2 is a matrix with ones where the second object is. The Overlap i can caluclate with np.logical_and(component == 1, component2 == 1). But how can I caclulate the Union? Im only interested in objects which are connected.

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)

Solution

  • If you're only dealing with 0 and 1, it's easier to work with boolean arrays:

    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