Skip to content

Référence pour ultralytics/trackers/utils/matching.py

Note

Ce fichier est disponible à l'adresse https://github.com/ultralytics/ ultralytics/blob/main/ ultralytics/trackers/utils/matching .py. Si tu repères un problème, aide à le corriger en contribuant à une Pull Request 🛠️. Merci 🙏 !



ultralytics.trackers.utils.matching.linear_assignment(cost_matrix, thresh, use_lap=True)

Effectue une affectation linéaire en utilisant scipy ou lap.lapjv.

Paramètres :

Nom Type Description DĂ©faut
cost_matrix ndarray

La matrice contenant les valeurs de coût pour les affectations.

requis
thresh float

Seuil à partir duquel une affectation est considérée comme valide.

requis
use_lap bool

Utiliser ou non lap.lapjv. La valeur par défaut est True.

True

Retourne :

Type Description
tuple

Tuple avec : - indices appariés - indices non appariés de 'a' - indices non appariés de 'b'

Code source dans ultralytics/trackers/utils/matching.py
def linear_assignment(cost_matrix: np.ndarray, thresh: float, use_lap: bool = True) -> tuple:
    """
    Perform linear assignment using scipy or lap.lapjv.

    Args:
        cost_matrix (np.ndarray): The matrix containing cost values for assignments.
        thresh (float): Threshold for considering an assignment valid.
        use_lap (bool, optional): Whether to use lap.lapjv. Defaults to True.

    Returns:
        Tuple with:
            - matched indices
            - unmatched indices from 'a'
            - unmatched indices from 'b'
    """

    if cost_matrix.size == 0:
        return np.empty((0, 2), dtype=int), tuple(range(cost_matrix.shape[0])), tuple(range(cost_matrix.shape[1]))

    if use_lap:
        # Use lap.lapjv
        # https://github.com/gatagat/lap
        _, x, y = lap.lapjv(cost_matrix, extend_cost=True, cost_limit=thresh)
        matches = [[ix, mx] for ix, mx in enumerate(x) if mx >= 0]
        unmatched_a = np.where(x < 0)[0]
        unmatched_b = np.where(y < 0)[0]
    else:
        # Use scipy.optimize.linear_sum_assignment
        # https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linear_sum_assignment.html
        x, y = scipy.optimize.linear_sum_assignment(cost_matrix)  # row x, col y
        matches = np.asarray([[x[i], y[i]] for i in range(len(x)) if cost_matrix[x[i], y[i]] <= thresh])
        if len(matches) == 0:
            unmatched_a = list(np.arange(cost_matrix.shape[0]))
            unmatched_b = list(np.arange(cost_matrix.shape[1]))
        else:
            unmatched_a = list(set(np.arange(cost_matrix.shape[0])) - set(matches[:, 0]))
            unmatched_b = list(set(np.arange(cost_matrix.shape[1])) - set(matches[:, 1]))

    return matches, unmatched_a, unmatched_b



ultralytics.trackers.utils.matching.iou_distance(atracks, btracks)

Calculer le coût en fonction de l'intersection sur l'union (IoU) entre les voies.

Paramètres :

Nom Type Description DĂ©faut
atracks list[STrack] | list[ndarray]

Liste des pistes 'a' ou des boîtes de délimitation.

requis
btracks list[STrack] | list[ndarray]

Liste des pistes 'b' ou boîtes de délimitation.

requis

Retourne :

Type Description
ndarray

Matrice des coûts calculée sur la base du rapport coût-efficacité.

Code source dans ultralytics/trackers/utils/matching.py
def iou_distance(atracks: list, btracks: list) -> np.ndarray:
    """
    Compute cost based on Intersection over Union (IoU) between tracks.

    Args:
        atracks (list[STrack] | list[np.ndarray]): List of tracks 'a' or bounding boxes.
        btracks (list[STrack] | list[np.ndarray]): List of tracks 'b' or bounding boxes.

    Returns:
        (np.ndarray): Cost matrix computed based on IoU.
    """

    if atracks and isinstance(atracks[0], np.ndarray) or btracks and isinstance(btracks[0], np.ndarray):
        atlbrs = atracks
        btlbrs = btracks
    else:
        atlbrs = [track.xywha if track.angle is not None else track.xyxy for track in atracks]
        btlbrs = [track.xywha if track.angle is not None else track.xyxy for track in btracks]

    ious = np.zeros((len(atlbrs), len(btlbrs)), dtype=np.float32)
    if len(atlbrs) and len(btlbrs):
        if len(atlbrs[0]) == 5 and len(btlbrs[0]) == 5:
            ious = batch_probiou(
                np.ascontiguousarray(atlbrs, dtype=np.float32),
                np.ascontiguousarray(btlbrs, dtype=np.float32),
            ).numpy()
        else:
            ious = bbox_ioa(
                np.ascontiguousarray(atlbrs, dtype=np.float32),
                np.ascontiguousarray(btlbrs, dtype=np.float32),
                iou=True,
            )
    return 1 - ious  # cost matrix



ultralytics.trackers.utils.matching.embedding_distance(tracks, detections, metric='cosine')

Calcule la distance entre les pistes et les détections sur la base de l'intégration.

Paramètres :

Nom Type Description DĂ©faut
tracks list[STrack]

Liste des titres.

requis
detections list[BaseTrack]

Liste des détections.

requis
metric str

Métrique pour le calcul de la distance. La valeur par défaut est "cosinus".

'cosine'

Retourne :

Type Description
ndarray

Matrice des coûts calculée sur la base de l'intégration.

Code source dans ultralytics/trackers/utils/matching.py
def embedding_distance(tracks: list, detections: list, metric: str = "cosine") -> np.ndarray:
    """
    Compute distance between tracks and detections based on embeddings.

    Args:
        tracks (list[STrack]): List of tracks.
        detections (list[BaseTrack]): List of detections.
        metric (str, optional): Metric for distance computation. Defaults to 'cosine'.

    Returns:
        (np.ndarray): Cost matrix computed based on embeddings.
    """

    cost_matrix = np.zeros((len(tracks), len(detections)), dtype=np.float32)
    if cost_matrix.size == 0:
        return cost_matrix
    det_features = np.asarray([track.curr_feat for track in detections], dtype=np.float32)
    # for i, track in enumerate(tracks):
    # cost_matrix[i, :] = np.maximum(0.0, cdist(track.smooth_feat.reshape(1,-1), det_features, metric))
    track_features = np.asarray([track.smooth_feat for track in tracks], dtype=np.float32)
    cost_matrix = np.maximum(0.0, cdist(track_features, det_features, metric))  # Normalized features
    return cost_matrix



ultralytics.trackers.utils.matching.fuse_score(cost_matrix, detections)

Fusionne la matrice des coûts avec les scores de détection pour produire une seule matrice de similarité.

Paramètres :

Nom Type Description DĂ©faut
cost_matrix ndarray

La matrice contenant les valeurs de coût pour les affectations.

requis
detections list[BaseTrack]

Liste des détections avec les scores.

requis

Retourne :

Type Description
ndarray

Matrice de similarité fusionnée.

Code source dans ultralytics/trackers/utils/matching.py
def fuse_score(cost_matrix: np.ndarray, detections: list) -> np.ndarray:
    """
    Fuses cost matrix with detection scores to produce a single similarity matrix.

    Args:
        cost_matrix (np.ndarray): The matrix containing cost values for assignments.
        detections (list[BaseTrack]): List of detections with scores.

    Returns:
        (np.ndarray): Fused similarity matrix.
    """

    if cost_matrix.size == 0:
        return cost_matrix
    iou_sim = 1 - cost_matrix
    det_scores = np.array([det.score for det in detections])
    det_scores = np.expand_dims(det_scores, axis=0).repeat(cost_matrix.shape[0], axis=0)
    fuse_sim = iou_sim * det_scores
    return 1 - fuse_sim  # fuse_cost





Created 2023-11-12, Updated 2024-06-02
Authors: glenn-jocher (5), Burhan-Q (1), Laughing-q (1)