Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 742
Liwellyen Avatar asked Dec 24 '22 08:12

Liwellyen


2 Answers

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
like image 92
dROOOze Avatar answered Dec 26 '22 10:12

dROOOze


Oleksii has an answer for your question in medium.

Simply put:

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)

Also, he gives a very good explains of it. Take a look at the above link.

like image 28
Mai Hai Avatar answered Dec 26 '22 11:12

Mai Hai