Created
August 6, 2018 10:15
-
-
Save sunsided/5b50fa1a7329fe8f3fdc49ec78c25d41 to your computer and use it in GitHub Desktop.
Intersection over Union (Jaccard index)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Tuple | |
def jaccard(a: Tuple[int, int, int, int], b: Tuple[int, int, int, int]) -> float: | |
ax, ay, aw, ah = a | |
bx, by, bw, bh = b | |
left_i = max(ax, bx) | |
top_i = max(ay, by) | |
right_i = min(ax + aw, bx + bw) | |
bottom_i = min(ay + ah, by + bh) | |
# If the boxes don't overlap, the smallest right/bottom coordinate | |
# will be less than the biggest left/top one. | |
if right_i < left_i or bottom_i < top_i: | |
return 0 | |
# Intersection and box areas | |
intersection_area = (right_i - left_i) * (bottom_i - top_i) | |
area_a = ah * aw | |
area_b = bh * bw | |
# If the boxes still have a zero intersection (e.g. because they overlap, | |
# but their area is zero), we return zero. | |
if intersection_area < 1e-6: | |
return 0 | |
union_area = area_a + area_b - intersection_area | |
return intersection_area / union_area |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment