|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from abc import ABC, abstractmethod |
| 4 | +from copy import deepcopy |
| 5 | +from typing import TYPE_CHECKING, Sequence, TypeVar |
| 6 | + |
| 7 | +import numpy as np |
| 8 | + |
| 9 | +from ..result import BoxMatch |
| 10 | + |
| 11 | +if TYPE_CHECKING: |
| 12 | + from t4_devkit.dataclass import BoxLike |
| 13 | + from t4_devkit.typing import NDArrayF64 |
| 14 | + |
| 15 | + from .policy import MatchingPolicyLike |
| 16 | + from .scorer import MatchingScorerLike |
| 17 | + |
| 18 | +__all__ = ["GreedyMatcher", "MatchingAlgorithmLike"] |
| 19 | + |
| 20 | + |
| 21 | +# ===== Base Class for Matching Algorithm ===== |
| 22 | + |
| 23 | + |
| 24 | +class MatchingAlgorithmImpl(ABC): |
| 25 | + """Abstract base class for matching algorithm class.""" |
| 26 | + |
| 27 | + def __init__( |
| 28 | + self, |
| 29 | + scorer: MatchingScorerLike, |
| 30 | + policy: MatchingPolicyLike, |
| 31 | + matchable_threshold: float, |
| 32 | + ) -> None: |
| 33 | + super().__init__() |
| 34 | + self._scorer = scorer |
| 35 | + self._policy = policy |
| 36 | + self._matchable_threshold = matchable_threshold |
| 37 | + |
| 38 | + def __call__( |
| 39 | + self, |
| 40 | + estimations: Sequence[BoxLike], |
| 41 | + ground_truths: Sequence[BoxLike], |
| 42 | + ) -> list[BoxMatch]: |
| 43 | + """Execute matching. |
| 44 | +
|
| 45 | + Args: |
| 46 | + estimations (Sequence[BoxLike]): Sequence of estimations. |
| 47 | + ground_truths (Sequence[BoxLike]): Sequence of ground truths. |
| 48 | +
|
| 49 | + Returns: |
| 50 | + list[BoxMatch]: List of matches. |
| 51 | + """ |
| 52 | + score_table = self._score_table(estimations, ground_truths) |
| 53 | + return self._do_matching(estimations, ground_truths, score_table) |
| 54 | + |
| 55 | + def _score_table( |
| 56 | + self, |
| 57 | + estimations: Sequence[BoxLike], |
| 58 | + ground_truths: Sequence[BoxLike], |
| 59 | + ) -> NDArrayF64: |
| 60 | + """Create a score table. |
| 61 | +
|
| 62 | + Args: |
| 63 | + estimations (Sequence[BoxLike]): Sequence of estimations. |
| 64 | + ground_truths (Sequence[BoxLike]): Sequence of ground truths. |
| 65 | +
|
| 66 | + Returns: |
| 67 | + NDArrayF64: Score table in the shape of (NumEst, NumGT). |
| 68 | + """ |
| 69 | + num_rows, num_cols = len(estimations), len(ground_truths) |
| 70 | + |
| 71 | + table: NDArrayF64 = np.full((num_rows, num_cols), fill_value=np.nan) |
| 72 | + for i, box1 in enumerate(estimations): |
| 73 | + for j, box2 in enumerate(ground_truths): |
| 74 | + if box1.frame_id != box2.frame_id: |
| 75 | + continue |
| 76 | + |
| 77 | + score = self._scorer(box1, box2) |
| 78 | + |
| 79 | + # check if boxes distance and label is matchable |
| 80 | + if self._scorer.is_better_than( |
| 81 | + score, self._matchable_threshold |
| 82 | + ) and self._policy.is_matchable(box1, box2): |
| 83 | + table[i, j] = score |
| 84 | + |
| 85 | + return table |
| 86 | + |
| 87 | + def _get_indices(self, score_table: NDArrayF64) -> tuple[int, int]: |
| 88 | + """Return indices of estimation and ground truth in the score table at the best score. |
| 89 | +
|
| 90 | + Args: |
| 91 | + score_table (NDArrayF64): Score table in the shape of (NumEst, NumGt). |
| 92 | +
|
| 93 | + Returns: |
| 94 | + Estimation index and ground truth index. |
| 95 | + """ |
| 96 | + estimation_idx, ground_truth_idx = ( |
| 97 | + np.unravel_index(np.nanargmin(score_table), score_table.shape) |
| 98 | + if self._scorer.is_smaller_score_better() |
| 99 | + else np.unravel_index(np.nanargmax(score_table), score_table.shape) |
| 100 | + ) |
| 101 | + return estimation_idx, ground_truth_idx |
| 102 | + |
| 103 | + @abstractmethod |
| 104 | + def _do_matching( |
| 105 | + self, |
| 106 | + estimations: Sequence[BoxLike], |
| 107 | + ground_truths: Sequence[BoxLike], |
| 108 | + score_table: NDArrayF64, |
| 109 | + ) -> list[BoxMatch]: |
| 110 | + pass |
| 111 | + |
| 112 | + |
| 113 | +MatchingAlgorithmLike = TypeVar("MatchingAlgorithmLike", bound=MatchingAlgorithmImpl) |
| 114 | + |
| 115 | + |
| 116 | +# ===== Specific Matching Algorithms ===== |
| 117 | + |
| 118 | + |
| 119 | +class GreedyMatcher(MatchingAlgorithmImpl): |
| 120 | + def _do_matching( |
| 121 | + self, |
| 122 | + estimations: Sequence[BoxLike], |
| 123 | + ground_truths: Sequence[BoxLike], |
| 124 | + score_table: NDArrayF64, |
| 125 | + ) -> list[BoxMatch]: |
| 126 | + tmp_estimations = list(deepcopy(estimations)) |
| 127 | + tmp_ground_truths = list(deepcopy(ground_truths)) |
| 128 | + |
| 129 | + output: list[BoxMatch] = [] |
| 130 | + # 1. match the nearest matchable estimations and GTs |
| 131 | + num_estimations, *_ = score_table.shape |
| 132 | + for _ in range(num_estimations): |
| 133 | + if np.isnan(score_table).all(): |
| 134 | + break |
| 135 | + |
| 136 | + estimation_idx, ground_truth_idx = self._get_indices(score_table) |
| 137 | + |
| 138 | + estimation_picked = tmp_estimations.pop(estimation_idx) |
| 139 | + ground_truth_picked = tmp_ground_truths.pop(ground_truth_idx) |
| 140 | + output.append(BoxMatch(estimation_picked, ground_truth_picked)) |
| 141 | + |
| 142 | + # remove picked estimations and GTs |
| 143 | + score_table = np.delete(score_table, estimation_idx, axis=0) |
| 144 | + score_table = np.delete(score_table, ground_truth_idx, axis=1) |
| 145 | + |
| 146 | + # 2. assign remaining estimations(=FPs) and GTs(=FNs) |
| 147 | + output += [BoxMatch(estimation=estimation) for estimation in tmp_estimations] |
| 148 | + output += [BoxMatch(ground_truth=ground_truth) for ground_truth in tmp_ground_truths] |
| 149 | + |
| 150 | + return output |
0 commit comments