a
    yfRQ                     @   sj   d dl ZddlmZ ddlmZ ddlmZmZ ddlm	Z	 ddl
mZ G d	d
 d
eZG dd dZdS )    N   )LOGGER)	xywh2ltwh   )	BaseTrack
TrackState)matchingKalmanFilterXYAHc                       s   e Zd ZdZe Z fddZdd Zedd Z	ee
dd	fd
dZdd Zd#ddZdd Zdd Zedd Zedd Zedd Zedd Zedd Zedd  Zd!d" Z  ZS )$STracka  
    Single object tracking representation that uses Kalman filtering for state estimation.

    This class is responsible for storing all the information regarding individual tracklets and performs state updates
    and predictions based on Kalman filter.

    Attributes:
        shared_kalman (KalmanFilterXYAH): Shared Kalman filter that is used across all STrack instances for prediction.
        _tlwh (np.ndarray): Private attribute to store top-left corner coordinates and width and height of bounding box.
        kalman_filter (KalmanFilterXYAH): Instance of Kalman filter used for this particular object track.
        mean (np.ndarray): Mean state estimate vector.
        covariance (np.ndarray): Covariance of state estimate.
        is_activated (bool): Boolean flag indicating if the track has been activated.
        score (float): Confidence score of the track.
        tracklet_len (int): Length of the tracklet.
        cls (Any): Class label for the object.
        idx (int): Index or identifier for the object.
        frame_id (int): Current frame ID.
        start_frame (int): Frame where the object was first detected.

    Methods:
        predict(): Predict the next state of the object using Kalman filter.
        multi_predict(stracks): Predict the next states for multiple tracks.
        multi_gmc(stracks, H): Update multiple track states using a homography matrix.
        activate(kalman_filter, frame_id): Activate a new tracklet.
        re_activate(new_track, frame_id, new_id): Reactivate a previously lost tracklet.
        update(new_track, frame_id): Update the state of a matched track.
        convert_coords(tlwh): Convert bounding box to x-y-aspect-height format.
        tlwh_to_xyah(tlwh): Convert tlwh bounding box to xyah format.

    Examples:
        Initialize and activate a new track
        >>> track = STrack(xywh=[100, 200, 50, 80, 0], score=0.9, cls="person")
        >>> track.activate(kalman_filter=KalmanFilterXYAH(), frame_id=1)
    c                    s   t    t|dv s(J dt| tjt|dd tjd| _d| _d\| _	| _
d| _|| _d| _|| _|d	 | _t|d
kr|d nd| _dS )aX  
        Initialize a new STrack instance.

        Args:
            xywh (List[float]): Bounding box coordinates and dimensions in the format (x, y, w, h, [a], idx), where
                (x, y) is the center, (w, h) are width and height, [a] is optional aspect ratio, and idx is the id.
            score (float): Confidence score of the detection.
            cls (Any): Class label for the detected object.

        Examples:
            >>> xywh = [100.0, 150.0, 50.0, 75.0, 1]
            >>> score = 0.9
            >>> cls = "person"
            >>> track = STrack(xywh, score, cls)
        >         zexpected 5 or 6 values but got N   Zdtype)NNFr   r   )super__init__lennpasarrayr   float32_tlwhkalman_filtermean
covarianceis_activatedscoretracklet_lenclsidxangle)selfxywhr   r   	__class__ ]/var/www/html/django/DPS/env/lib/python3.9/site-packages/ultralytics/trackers/byte_tracker.pyr   3   s    

zSTrack.__init__c                 C   s:   | j  }| jtjkrd|d< | j|| j\| _ | _dS )zTPredicts the next state (mean and covariance) of the object using the Kalman filter.r      N)r   copystater   Trackedr   predictr   )r!   Z
mean_stater%   r%   r&   r+   Q   s    
zSTrack.predictc                 C   s   t | dkrdS tdd | D }tdd | D }t| D ] \}}|jtjkr@d|| d< q@tj	||\}}tt
||D ] \}\}}|| | _|| | _qdS )zgPerform multi-object predictive tracking using Kalman filter for the provided list of STrack instances.r   Nc                 S   s   g | ]}|j  qS r%   r   r(   .0str%   r%   r&   
<listcomp>]       z(STrack.multi_predict.<locals>.<listcomp>c                 S   s   g | ]
}|j qS r%   r   r-   r%   r%   r&   r0   ^   r1   r'   )r   r   r   	enumerater)   r   r*   r   shared_kalmanmulti_predictzipr   r   )stracks
multi_meanmulti_covarianceir/   r   covr%   r%   r&   r5   X   s    
zSTrack.multi_predictr      c           
      C   s   t | dkrtdd | D }tdd | D }|ddddf }ttjdtd|}|dddf }tt||D ]R\}\}}	||}|dd  |7  < ||	|	 }	|| | _
|	| | _q|dS )	z\Update state tracks positions and covariances using a homography matrix for multiple tracks.r   c                 S   s   g | ]}|j  qS r%   r,   r-   r%   r%   r&   r0   k   r1   z$STrack.multi_gmc.<locals>.<listcomp>c                 S   s   g | ]
}|j qS r%   r2   r-   r%   r%   r&   r0   l   r1   Nr   r   r   )r   r   r   Zkroneyefloatr3   r6   dotZ	transposer   r   )
r7   Hr8   r9   RZR8x8tr:   r   r;   r%   r%   r&   	multi_gmcg   s    

zSTrack.multi_gmcc                 C   sX   || _ |  | _| j | | j\| _| _d| _t	j
| _|dkrHd| _|| _|| _dS )zaActivate a new tracklet using the provided Kalman filter and initialize its state and covariance.r   r   TN)r   next_idtrack_idZinitiateconvert_coordsr   r   r   r   r   r*   r)   r   frame_idstart_frame)r!   r   rG   r%   r%   r&   activatez   s    
zSTrack.activateFc                 C   sp   | j | j| j| |j\| _| _d| _tj| _	d| _
|| _|rL|  | _|j| _|j| _|j| _|j| _dS )zbReactivates a previously lost track using new detection data and updates its state and attributes.r   TN)r   updater   r   rF   tlwhr   r   r*   r)   r   rG   rD   rE   r   r   r    r   )r!   	new_trackrG   new_idr%   r%   r&   re_activate   s    
zSTrack.re_activatec                 C   sn   || _ |  jd7  _|j}| j| j| j| |\| _| _tj	| _
d| _|j| _|j| _|j| _|j| _dS )a  
        Update the state of a matched track.

        Args:
            new_track (STrack): The new track containing updated information.
            frame_id (int): The ID of the current frame.

        Examples:
            Update the state of a track with new detection information
            >>> track = STrack([100, 200, 50, 80, 0.9, 1])
            >>> new_track = STrack([105, 205, 55, 85, 0.95, 1])
            >>> track.update(new_track, 2)
        r   TN)rG   r   rK   r   rJ   r   r   rF   r   r*   r)   r   r   r   r    r   )r!   rL   rG   Znew_tlwhr%   r%   r&   rJ      s    zSTrack.updatec                 C   s
   |  |S )zZConvert a bounding box's top-left-width-height format to its x-y-aspect-height equivalent.)tlwh_to_xyah)r!   rK   r%   r%   r&   rF      s    zSTrack.convert_coordsc                 C   s^   | j du r| j S | j dd  }|d  |d 9  < |dd  |dd d 8  < |S )zYReturns the bounding box in top-left-width-height format from the current state estimate.Nr   r   r<   )r   r   r(   r!   retr%   r%   r&   rK      s    

 zSTrack.tlwhc                 C   s*   | j  }|dd  |dd 7  < |S )zjConverts bounding box from (top left x, top left y, width, height) to (min x, min y, max x, max y) format.r   N)rK   r(   rP   r%   r%   r&   xyxy   s    
zSTrack.xyxyc                 C   sF   t |  }|dd  |dd d 7  < |d  |d   < |S )zWConvert bounding box from tlwh format to center-x-center-y-aspect-height (xyah) format.Nr   r<   )r   r   r(   )rK   rQ   r%   r%   r&   rO      s     zSTrack.tlwh_to_xyahc                 C   s4   t | j }|dd  |dd d 7  < |S )z_Returns the current position of the bounding box in (center x, center y, width, height) format.Nr   )r   r   rK   r(   rP   r%   r%   r&   r"      s     zSTrack.xywhc                 C   s0   | j du rtd | jS t| j| j d gS )zcReturns position in (center x, center y, width, height, angle) format, warning if angle is missing.Nu@   WARNING ⚠️ `angle` attr not found, returning `xywh` instead.)r    r   warningr"   r   concatenater!   r%   r%   r&   xywha   s    

zSTrack.xywhac                 C   s2   | j du r| jn| j}| | j| j| j| jg S )zLReturns the current tracking results in the appropriate bounding box format.N)r    rR   rV   tolistrE   r   r   r   )r!   Zcoordsr%   r%   r&   result   s    zSTrack.resultc                 C   s   d| j  d| j d| j dS )zdReturns a string representation of the STrack object including start frame, end frame, and track ID.ZOT_z_(-))rE   rH   	end_framerU   r%   r%   r&   __repr__   s    zSTrack.__repr__)F)__name__
__module____qualname____doc__r
   r4   r   r+   staticmethodr5   r   r=   rC   rI   rN   rJ   rF   propertyrK   rR   rO   r"   rV   rX   r\   __classcell__r%   r%   r#   r&   r      s2   $


	




r   c                   @   s~   e Zd ZdZdddZdddZdd	 Zdd
dZdd Zdd Z	e
dd Zdd Ze
dd Ze
dd Ze
dd ZdS )BYTETrackera;  
    BYTETracker: A tracking algorithm built on top of YOLOv8 for object detection and tracking.

    Responsible for initializing, updating, and managing the tracks for detected objects in a video sequence.
    It maintains the state of tracked, lost, and removed tracks over frames, utilizes Kalman filtering for predicting
    the new object locations, and performs data association.

    Attributes:
        tracked_stracks (List[STrack]): List of successfully activated tracks.
        lost_stracks (List[STrack]): List of lost tracks.
        removed_stracks (List[STrack]): List of removed tracks.
        frame_id (int): The current frame ID.
        args (Namespace): Command-line arguments.
        max_time_lost (int): The maximum frames for a track to be considered as 'lost'.
        kalman_filter (KalmanFilterXYAH): Kalman Filter object.

    Methods:
        update(results, img=None): Updates object tracker with new detections.
        get_kalmanfilter(): Returns a Kalman filter object for tracking bounding boxes.
        init_track(dets, scores, cls, img=None): Initialize object tracking with detections.
        get_dists(tracks, detections): Calculates the distance between tracks and detections.
        multi_predict(tracks): Predicts the location of tracks.
        reset_id(): Resets the ID counter of STrack.
        joint_stracks(tlista, tlistb): Combines two lists of stracks.
        sub_stracks(tlista, tlistb): Filters out the stracks present in the second list from the first list.
        remove_duplicate_stracks(stracksa, stracksb): Removes duplicate stracks based on IoU.

    Examples:
        Initialize BYTETracker and update with detection results
        >>> tracker = BYTETracker(args, frame_rate=30)
        >>> results = yolo_model.detect(image)
        >>> tracked_objects = tracker.update(results)
       c                 C   sH   g | _ g | _g | _d| _|| _t|d |j | _|  | _	| 
  dS )a  
        Initialize a BYTETracker instance for object tracking.

        Args:
            args (Namespace): Command-line arguments containing tracking parameters.
            frame_rate (int): Frame rate of the video sequence.

        Examples:
            Initialize BYTETracker with command-line arguments and a frame rate of 30
            >>> args = Namespace(track_buffer=30)
            >>> tracker = BYTETracker(args, frame_rate=30)
        r   g      >@N)tracked_strackslost_stracksremoved_stracksrG   argsintZtrack_buffermax_time_lostget_kalmanfilterr   reset_id)r!   ri   Z
frame_rater%   r%   r&   r     s    
zBYTETracker.__init__Nc           %         sz  |  j d7  _ g }g }g }g }|j}t|dr4|jn|j}tj|tt|	ddgdd}|j
}	|| jjk}
|| jjk}|| jjk }||@ }|| }||
 }||
 }|| }|	|
 }|	| }| |||| g }g }| jD ] }|js|| q|| q| || j|  t| drT|durT| j||}t| t|| |  }tj|| jjd\}}}|D ]^\}}| } | }|jtjkr| || j  || n|j!|| j dd	 || q|| ||||}fd
d|D } t"| |}tj|dd\}}}!|D ]^\}}| | }|| }|jtjkrb| || j  || n|j!|| j dd	 || q"|D ].}"| |" }|jtj#kr|$  || q fdd|D  | | }tj|dd\}}#}|D ].\}}||   | | j  |||  q|#D ] }"||" }|%  || q |D ]<}$ |$ }|j&| jj'k rfqF|(| j)| j  || qF| jD ],}| j |j* | j+kr|%  || qdd | jD | _| | j|| _| | j|| _| ,| j| j| _| j-| | ,| j| j.| _| /| j| j\| _| _| j.-| t| j.dkr^| j.dd | _.tj0dd | jD tj1dS )zXUpdates the tracker with new detections and returns the current list of tracked objects.r   xywhrr   )ZaxisgmcN)ZthreshF)rM   c                    s$   g | ]} | j tjkr | qS r%   r)   r   r*   r.   r:   )strack_poolr%   r&   r0   _  r1   z&BYTETracker.update.<locals>.<listcomp>g      ?c                    s   g | ]} | qS r%   r%   rq   )
detectionsr%   r&   r0   s  r1   gffffff?c                 S   s   g | ]}|j tjkr|qS r%   rp   r.   rB   r%   r%   r&   r0     r1   i  ic                 S   s   g | ]}|j r|jqS r%   )r   rX   )r.   xr%   r%   r&   r0     r1   r   )2rG   confhasattrrn   r"   r   rT   Zaranger   Zreshaper   ri   Ztrack_high_threshZtrack_low_thresh
init_trackrf   r   appendjoint_stracksrg   r5   ro   applyr   rC   	get_distsr   Zlinear_assignmentZmatch_threshr)   r   r*   rJ   rN   iou_distanceZLostZ	mark_lostZmark_removedr   Znew_track_threshrI   r   r[   rk   sub_stracksextendrh   remove_duplicate_stracksr   r   )%r!   resultsimgZactivated_stracksZrefind_stracksrg   rh   scoresZbboxesr   Zremain_indsZinds_lowZ	inds_highZinds_secondZdets_seconddetsZscores_keepZscores_secondZcls_keepZ
cls_secondZunconfirmedrf   trackZwarpdistsmatchesZu_trackZu_detectionZitrackedZidetZdetZdetections_secondZr_tracked_stracksZu_detection_seconditZu_unconfirmedZinewr%   )rs   rr   r&   rJ   %  s    $


zBYTETracker.updatec                 C   s   t  S )zRReturns a Kalman filter object for tracking bounding boxes using KalmanFilterXYAH.r	   rU   r%   r%   r&   rl     s    zBYTETracker.get_kalmanfilterc                 C   s"   t |rdd t|||D S g S )zgInitializes object tracking with given detections, scores, and class labels using the STrack algorithm.c                 S   s   g | ]\}}}t |||qS r%   )r   )r.   rR   scr%   r%   r&   r0     r1   z*BYTETracker.init_track.<locals>.<listcomp>)r   r6   )r!   r   r   r   r   r%   r%   r&   rx     s    zBYTETracker.init_trackc                 C   s$   t ||}| jjr t ||}|S )z\Calculates the distance between tracks and detections using IoU and optionally fuses scores.)r   r}   ri   Z
fuse_score)r!   tracksrs   r   r%   r%   r&   r|     s    zBYTETracker.get_distsc                 C   s   t | dS )z@Predict the next states for multiple tracks using Kalman filter.N)r   r5   )r!   r   r%   r%   r&   r5     s    zBYTETracker.multi_predictc                   C   s   t   dS )z_Resets the ID counter for STrack instances to ensure unique track IDs across tracking sessions.N)r   rm   r%   r%   r%   r&   rm     s    zBYTETracker.reset_idc                 C   s.   g | _ g | _g | _d| _|  | _|   dS )zjResets the tracker by clearing all tracked, lost, and removed tracks and reinitializing the Kalman filter.r   N)rf   rg   rh   rG   rl   r   rm   rU   r%   r%   r&   reset  s    
zBYTETracker.resetc                 C   sX   i }g }| D ]}d||j < || q|D ](}|j }||ds*d||< || q*|S )zcCombines two lists of STrack objects into a single list, ensuring no duplicates based on track IDs.r   r   )rE   ry   get)tlistatlistbexistsresrB   tidr%   r%   r&   rz     s    
zBYTETracker.joint_stracksc                    s    dd |D   fdd| D S )zGFilters out the stracks present in the second list from the first list.c                 S   s   h | ]
}|j qS r%   rE   rt   r%   r%   r&   	<setcomp>  r1   z*BYTETracker.sub_stracks.<locals>.<setcomp>c                    s   g | ]}|j  vr|qS r%   r   rt   Ztrack_ids_br%   r&   r0     r1   z+BYTETracker.sub_stracks.<locals>.<listcomp>r%   )r   r   r%   r   r&   r~     s    zBYTETracker.sub_stracksc           
         s   t | |}t|dk }g g   t| D ]N\}}| | j| | j }|| j|| j }||krp| q, | q, fddt| D }fddt|D }	||	fS )zYRemoves duplicate stracks from two lists based on Intersection over Union (IoU) distance.g333333?c                    s   g | ]\}}| vr|qS r%   r%   r.   r:   rB   )dupar%   r&   r0     r1   z8BYTETracker.remove_duplicate_stracks.<locals>.<listcomp>c                    s   g | ]\}}| vr|qS r%   r%   r   )dupbr%   r&   r0     r1   )	r   r}   r   wherer6   rG   rH   ry   r3   )
ZstracksaZstracksbZpdistpairspqZtimepZtimeqZresaZresbr%   )r   r   r&   r     s    
z$BYTETracker.remove_duplicate_stracks)re   )N)N)r]   r^   r_   r`   r   rJ   rl   rx   r|   r5   ra   rm   r   rz   r~   r   r%   r%   r%   r&   rd      s    "

r

	

rd   )numpyr   utilsr   Z	utils.opsr   Z	basetrackr   r   r   Zutils.kalman_filterr
   r   rd   r%   r%   r%   r&   <module>   s    `