o
    oi:                     @  s   d dl mZ d dlZd dlZd dlZd dlmZ d dlmZm	Z	m
Z
 d dlmZ d dlmZmZ d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZ d dlmZ dgZeeZG dd dZ dS )    )annotationsN)Path)AnyOptionalUnion)kornia_config)Tensortensor)boxmot)numpy)write_image)ObjectDetector)RTDETRDetectorBuilder)tensor_to_imageBoxMotTrackerc                      s^   e Zd ZU dZdZded< 						d$d% fddZd&ddZd'd(ddZd)d*d"d#Z	  Z
S )+r   a#	  BoxMotTracker is a module that wraps a detector and a tracker model.

    This module uses BoxMot library for tracking.

    Args:
        detector: ObjectDetector: The detector model.
        tracker_model_name: The name of the tracker model. Valid options are:
            - "BoTSORT"
            - "DeepOCSORT"
            - "OCSORT"
            - "HybridSORT"
            - "ByteTrack"
            - "StrongSORT"
            - "ImprAssoc"
        tracker_model_weights: Path to the model weights for ReID (Re-Identification).
        device: Device on which to run the model (e.g., 'cpu' or 'cuda').
        fp16: Whether to use half-precision (fp16) for faster inference on compatible devices.
        per_class: Whether to perform per-class tracking
        track_high_thresh: High threshold for detection confidence.
            Detections above this threshold are used in the first association round.
        track_low_thresh: Low threshold for detection confidence.
            Detections below this threshold are ignored.
        new_track_thresh: Threshold for creating a new track.
            Detections above this threshold will be considered as potential new tracks.
        track_buffer: Number of frames to keep a track alive after it was last detected.
        match_thresh: Threshold for the matching step in data association.
        proximity_thresh: Threshold for IoU (Intersection over Union) distance in first-round association.
        appearance_thresh: Threshold for appearance embedding distance in the ReID module.
        cmc_method: Method for correcting camera motion. Options include "sof" (simple optical flow).
        frame_rate: Frame rate of the video being processed. Used to scale the track buffer size.
        fuse_first_associate: Whether to fuse appearance and motion information during the first association step.
        with_reid: Whether to use ReID (Re-Identification) features for association.

    .. code-block:: python

        import kornia
        image = kornia.utils.sample.get_sample_images()[0][None]
        model = BoxMotTracker()
        for i in range(4):  # At least 4 frames are needed to initialize the tracking position
            model.update(image)
        model.save(image)

    .. note::
        At least 4 frames are needed to initialize the tracking position.

    boxmot_trackerstrnamertdetr_r18vd
DeepOCSORTosnet_x0_25_msmt17.ptcpuFdetectorUnion[ObjectDetector, str]tracker_model_nametracker_model_weightsdevicefp16boolkwargsr   returnNonec                   s   t    t|tr|drtj|d}ntd| d|| _t	j
tj ddd tt|d	tt	jtj d|||d|| _d S )
Nrtdetr)
model_namez
Detector `zA` not available. You may pass an ObjectDetector instance instead.z/boxmotTexist_ok)model_weightsr   r    )super__init__
isinstancer   
startswithr   build
ValueErrorr   osmakedirsr   hub_models_dirgetattrr
   r   pathjointracker)selfr   r   r   r   r   r   	__class__r'   Y/home/ubuntu/.local/lib/python3.10/site-packages/kornia/models/tracking/boxmot_tracker.pyr)   Z   s    
	



zBoxMotTracker.__init__imager   c              
   C  s  |j dkr|jd dks|j dkstd|j |j dkr#|d}| |}|d   }t|dddf |dddf |dddf |dddf  |dddf |dddf  |dddf |dddf gj	}|jd dkr|t
d	}t|d
 tj}| j||S )zaUpdate the tracker with a new image.

        Args:
            image: The input image.

           r         z=Input tensor must be of shape (1, 3, H, W) or (3, H, W). Got N      )r         )ndimshaper-   	unsqueezer   r   r   nparrayTemptyr   astypeuint8r4   update)r5   r9   detections_raw
detections	frame_rawr'   r'   r8   rJ   t   s*   "


	
zBoxMotTracker.updateTshow_trajectoriesc                 C  s6   t |d tj}| jj||d t|dddS )zVisualize the results of the tracker.

        Args:
            image: The input image.
            show_trajectories: Whether to show the trajectories.

        Returns:
            The image with the results of the tracker.

        r@   rN   r=   r   r;   )r   rH   rD   rI   r4   plot_resultsr	   permute)r5   r9   rN   rM   r'   r'   r8   	visualize   s   zBoxMotTracker.visualizeN	directoryOptional[str]c                 C  s   |du r| j  dtjjtjjdd}tjd|}| j	||d}tj
|dd ttj|td	d
 d|  td|  dS )zSave the model to ONNX format.

        Args:
            image: The input image.
            show_trajectories: Whether to visualize trajectories.
            directory: Where to save the file(s).

        N_)tzz%Y%m%d%H%M%Skornia_outputsrO   Tr$   r   r?   z.jpgzOutputs are saved in )r   datetimenowtimezoneutcstrftimer.   r2   r3   rR   r/   r   r   zfillbyteloggerinfo)r5   r9   rN   rS   r   outputr'   r'   r8   save   s   	$zBoxMotTracker.save)r   r   r   r   F)r   r   r   r   r   r   r   r   r   r   r   r   r    r!   )r9   r   r    r!   )T)r9   r   rN   r   r    r   )TN)r9   r   rN   r   rS   rT   r    r!   )__name__
__module____qualname____doc__r   __annotations__r)   rJ   rR   rb   __classcell__r'   r'   r6   r8   r   (   s   
 /
$)!
__future__r   rX   loggingr.   pathlibr   typingr   r   r   kornia.configr   kornia.corer   r	   kornia.core.externalr
   r   rD   	kornia.ior   kornia.models.detection.baser   kornia.models.detection.rtdetrr   kornia.utils.imager   __all__	getLoggerrc   r_   r   r'   r'   r'   r8   <module>   s"   
