Saltar al contenido

Referencia para ultralytics/trackers/basetrack.py

Nota

Este archivo está disponible en https://github.com/ultralytics/ ultralytics/blob/main/ ultralytics/trackers/basetrack .py. Si detectas algún problema, por favor, ayuda a solucionarlo contribuyendo con una Pull Request 🛠️. ¡Gracias 🙏!



ultralytics.trackers.basetrack.TrackState

Clase de enumeración que representa los posibles estados de un objeto rastreado.

Atributos:

Nombre Tipo Descripción
New int

Estado cuando el objeto se detecta de nuevo.

Tracked int

Estado cuando el objeto se rastrea con éxito en fotogramas posteriores.

Lost int

Estado en el que el objeto deja de ser rastreado.

Removed int

Estado en el que se retira el objeto del seguimiento.

Código fuente en ultralytics/trackers/basetrack.py
class TrackState:
    """
    Enumeration class representing the possible states of an object being tracked.

    Attributes:
        New (int): State when the object is newly detected.
        Tracked (int): State when the object is successfully tracked in subsequent frames.
        Lost (int): State when the object is no longer tracked.
        Removed (int): State when the object is removed from tracking.
    """

    New = 0
    Tracked = 1
    Lost = 2
    Removed = 3



ultralytics.trackers.basetrack.BaseTrack

Clase base para el seguimiento de objetos, que proporciona atributos y métodos fundamentales.

Atributos:

Nombre Tipo Descripción
_count int

Contador a nivel de clase para identificadores de pista únicos.

track_id int

Identificador único de la pista.

is_activated bool

Bandera que indica si la pista está actualmente activa.

state TrackState

Estado actual de la pista.

history OrderedDict

Historia ordenada de los estados de la pista.

features list

Lista de características extraídas del objeto para el seguimiento.

curr_feature any

La característica actual del objeto rastreado.

score float

La puntuación de confianza del seguimiento.

start_frame int

El número de fotograma en el que se inició el seguimiento.

frame_id int

El ID de fotograma más reciente procesado por la pista.

time_since_update int

Fotogramas transcurridos desde la última actualización.

location tuple

La ubicación del objeto en el contexto del seguimiento multicámara.

Métodos:

Nombre Descripción
end_frame

Devuelve el ID del último fotograma en el que se realizó el seguimiento del objeto.

next_id

Incrementa y devuelve el siguiente ID de pista global.

activate

Método abstracto para activar la pista.

predict

Método abstracto para predecir el siguiente estado de la pista.

update

Método abstracto para actualizar la pista con nuevos datos.

mark_lost

Marca la pista como perdida.

mark_removed

Marca la pista como eliminada.

reset_id

Pone a cero el contador global de ID de pista.

Código fuente en ultralytics/trackers/basetrack.py
class BaseTrack:
    """
    Base class for object tracking, providing foundational attributes and methods.

    Attributes:
        _count (int): Class-level counter for unique track IDs.
        track_id (int): Unique identifier for the track.
        is_activated (bool): Flag indicating whether the track is currently active.
        state (TrackState): Current state of the track.
        history (OrderedDict): Ordered history of the track's states.
        features (list): List of features extracted from the object for tracking.
        curr_feature (any): The current feature of the object being tracked.
        score (float): The confidence score of the tracking.
        start_frame (int): The frame number where tracking started.
        frame_id (int): The most recent frame ID processed by the track.
        time_since_update (int): Frames passed since the last update.
        location (tuple): The location of the object in the context of multi-camera tracking.

    Methods:
        end_frame: Returns the ID of the last frame where the object was tracked.
        next_id: Increments and returns the next global track ID.
        activate: Abstract method to activate the track.
        predict: Abstract method to predict the next state of the track.
        update: Abstract method to update the track with new data.
        mark_lost: Marks the track as lost.
        mark_removed: Marks the track as removed.
        reset_id: Resets the global track ID counter.
    """

    _count = 0

    def __init__(self):
        """Initializes a new track with unique ID and foundational tracking attributes."""
        self.track_id = 0
        self.is_activated = False
        self.state = TrackState.New
        self.history = OrderedDict()
        self.features = []
        self.curr_feature = None
        self.score = 0
        self.start_frame = 0
        self.frame_id = 0
        self.time_since_update = 0
        self.location = (np.inf, np.inf)

    @property
    def end_frame(self):
        """Return the last frame ID of the track."""
        return self.frame_id

    @staticmethod
    def next_id():
        """Increment and return the global track ID counter."""
        BaseTrack._count += 1
        return BaseTrack._count

    def activate(self, *args):
        """Abstract method to activate the track with provided arguments."""
        raise NotImplementedError

    def predict(self):
        """Abstract method to predict the next state of the track."""
        raise NotImplementedError

    def update(self, *args, **kwargs):
        """Abstract method to update the track with new observations."""
        raise NotImplementedError

    def mark_lost(self):
        """Mark the track as lost."""
        self.state = TrackState.Lost

    def mark_removed(self):
        """Mark the track as removed."""
        self.state = TrackState.Removed

    @staticmethod
    def reset_id():
        """Reset the global track ID counter."""
        BaseTrack._count = 0

end_frame property

Devuelve el ID del último fotograma de la pista.

__init__()

Inicializa una nueva pista con un ID único y atributos fundacionales de seguimiento.

Código fuente en ultralytics/trackers/basetrack.py
def __init__(self):
    """Initializes a new track with unique ID and foundational tracking attributes."""
    self.track_id = 0
    self.is_activated = False
    self.state = TrackState.New
    self.history = OrderedDict()
    self.features = []
    self.curr_feature = None
    self.score = 0
    self.start_frame = 0
    self.frame_id = 0
    self.time_since_update = 0
    self.location = (np.inf, np.inf)

activate(*args)

Método abstracto para activar la pista con los argumentos proporcionados.

Código fuente en ultralytics/trackers/basetrack.py
def activate(self, *args):
    """Abstract method to activate the track with provided arguments."""
    raise NotImplementedError

mark_lost()

Marca la pista como perdida.

Código fuente en ultralytics/trackers/basetrack.py
def mark_lost(self):
    """Mark the track as lost."""
    self.state = TrackState.Lost

mark_removed()

Marca la pista como retirada.

Código fuente en ultralytics/trackers/basetrack.py
def mark_removed(self):
    """Mark the track as removed."""
    self.state = TrackState.Removed

next_id() staticmethod

Incrementa y devuelve el contador global de ID de pista.

Código fuente en ultralytics/trackers/basetrack.py
@staticmethod
def next_id():
    """Increment and return the global track ID counter."""
    BaseTrack._count += 1
    return BaseTrack._count

predict()

Método abstracto para predecir el siguiente estado de la pista.

Código fuente en ultralytics/trackers/basetrack.py
def predict(self):
    """Abstract method to predict the next state of the track."""
    raise NotImplementedError

reset_id() staticmethod

Reinicia el contador global de ID de pista.

Código fuente en ultralytics/trackers/basetrack.py
@staticmethod
def reset_id():
    """Reset the global track ID counter."""
    BaseTrack._count = 0

update(*args, **kwargs)

Método abstracto para actualizar la pista con nuevas observaciones.

Código fuente en ultralytics/trackers/basetrack.py
def update(self, *args, **kwargs):
    """Abstract method to update the track with new observations."""
    raise NotImplementedError





Creado 2023-11-12, Actualizado 2024-05-08
Autores: Burhan-Q (1), glenn-jocher (3)