diff --git a/metrics/mean_iou/mean_iou.py b/metrics/mean_iou/mean_iou.py index 4c19864d3..3ddb64ea7 100644 --- a/metrics/mean_iou/mean_iou.py +++ b/metrics/mean_iou/mean_iou.py @@ -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, @@ -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 diff --git a/tests/test_mean_iou_histogram.py b/tests/test_mean_iou_histogram.py new file mode 100644 index 000000000..3b0dd04ab --- /dev/null +++ b/tests/test_mean_iou_histogram.py @@ -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)