Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions metrics/mean_iou/mean_iou.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,13 @@
}"""


def _count_labels(values, num_labels):
if num_labels > 0 and np.issubdtype(values.dtype, np.integer):
valid = (values >= 0) & (values < num_labels)
return np.bincount(values[valid].astype(np.intp, copy=False), minlength=num_labels)
return np.histogram(values, bins=num_labels, range=(0, num_labels - 1))[0]


def intersect_and_union(
pred_label,
label,
Expand Down Expand Up @@ -141,16 +148,15 @@ def intersect_and_union(
label = label - 1
label[label == 254] = 255

mask = label != ignore_index
mask = np.not_equal(label, ignore_index)
pred_label = pred_label[mask]
label = np.array(label)[mask]
label = label[mask]

intersect = pred_label[pred_label == label]

area_intersect = np.histogram(intersect, bins=num_labels, range=(0, num_labels - 1))[0]
area_pred_label = np.histogram(pred_label, bins=num_labels, range=(0, num_labels - 1))[0]
area_label = np.histogram(label, bins=num_labels, range=(0, num_labels - 1))[0]
area_intersect = _count_labels(intersect, num_labels)
area_pred_label = _count_labels(pred_label, num_labels)
area_label = _count_labels(label, num_labels)

area_union = area_pred_label + area_label - area_intersect

Expand Down
26 changes: 26 additions & 0 deletions tests/test_mean_iou_histogram.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from pathlib import Path

import numpy as np
import pytest

import evaluate


@pytest.mark.parametrize(
("predictions", "references", "num_labels", "iou"),
[
([[0, 1, 2, 255], [2, 1, 0, 255]], [[0, 1, 1, 255], [2, 2, 0, 2]], 3, [1.0, 1 / 3, 1 / 4]),
([[0, 1, 255]], [[0, 0, 255]], 1, [0.5]),
],
)
def test_mean_iou_counts_integer_labels(predictions, references, num_labels, iou):
pytest.importorskip("PIL")
path = Path(__file__).resolve().parents[1] / "metrics" / "mean_iou"
metric = evaluate.load(str(path), keep_in_memory=True)
result = metric.compute(
predictions=[np.array(predictions, dtype=np.uint8)],
references=[np.array(references, dtype=np.uint8)],
num_labels=num_labels,
ignore_index=255,
)
assert result["per_category_iou"] == pytest.approx(iou)