
    |hT                         d dl mZmZmZmZ 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e      Z G d d      Zy)    )AnyListOptionalTupleN   )LOGGER)	xywh2ltwh   )	BaseTrack
TrackState)matchingKalmanFilterXYAHc                   @    e Zd ZdZ e       Zdee   dedef fdZ	d Z
eded    fd       Ze ej                  d	d
      fded    dej                  fd       ZdedefdZddd dedefdZdd defdZdej                  dej                  fdZedej                  fd       Zedej                  fd       Zedej                  dej                  fd       Zedej                  fd       Zedej                  fd       Zedee   fd       ZdefdZ x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 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.
        angle (float | None): Optional angle information for oriented bounding boxes.

    Methods:
        predict: Predict the next state of the object using Kalman filter.
        multi_predict: Predict the next states for multiple tracks.
        multi_gmc: Update multiple track states using a homography matrix.
        activate: Activate a new tracklet.
        re_activate: Reactivate a previously lost tracklet.
        update: Update the state of a matched track.
        convert_coords: Convert bounding box to x-y-aspect-height format.
        tlwh_to_xyah: 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)
    xywhscoreclsc                    t         |           t        |      dv sJ dt        |              t        j                  t        |dd       t        j                        | _        d| _        d\  | _	        | _
        d| _        || _        d| _        || _        |d	   | _        t        |      d
k(  r|d   | _        yd| _        y)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   dtypeNNFr   r   )super__init__lennpasarrayr	   float32_tlwhkalman_filtermean
covarianceis_activatedr   tracklet_lenr   idxangle)selfr   r   r   	__class__s       `/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/trackers/byte_tracker.pyr   zSTrack.__init__6   s      	4yF"Q&Ec$i[$QQ"ZZ	$r( 32::F
!%/"	4?!
8 #D	QT!W
D
    c                     | j                   j                         }| j                  t        j                  k7  rd|d<   | j
                  j                  || j                        \  | _         | _        y)zSPredict the next state (mean and covariance) of the object using the Kalman filter.r      N)r%   copystater   Trackedr$   predictr&   )r+   
mean_states     r-   r4   zSTrack.predictT   sR    YY^^%
::+++JqM%)%7%7%?%?
DOO%\"	4?r.   stracksc                 &   t        |       dk  ryt        j                  | D cg c]  }|j                  j	                          c}      }t        j                  | D cg c]  }|j
                   c}      }t        |       D ]+  \  }}|j                  t        j                  k7  s$d||   d<   - t        j                  j                  ||      \  }}t        t        ||            D ]  \  }\  }}|| |   _        || |   _         yc c}w c c}w )zgPerform multi-object predictive tracking using Kalman filter for the provided list of STrack instances.r   Nr0   )r   r    r!   r%   r1   r&   	enumerater2   r   r3   r   shared_kalmanmulti_predictzip)r6   st
multi_meanmulti_covarianceir%   covs          r-   r:   zSTrack.multi_predict[   s     w<1ZZ' BB BC
::w&Gr}}&GHw' 	%EArxx:---#$
1a 	% (.';';'I'I*Vf'g$
$'J8H(IJ 	(NA{c"GAJO$'GAJ!	( !C&Gs   !D	Dr      Hc                    t        |       dkD  r-t        j                  | D cg c]  }|j                  j	                          c}      }t        j                  | D cg c]  }|j
                   c}      }|ddddf   }t        j                  t        j                  dt              |      }|dddf   }t        t        ||            D ]i  \  }\  }	}
|j                  |	      }	|	ddxxx |z  ccc |j                  |
      j                  |j                               }
|	| |   _        |
| |   _        k yyc c}w c c}w )z\Update state tracks positions and covariances using a homography matrix for multiple tracks.r   Nr   r   r   )r   r    r!   r%   r1   r&   kroneyefloatr8   r;   dot	transpose)r6   rB   r<   r=   r>   RR8x8tr?   r%   r@   s              r-   	multi_gmczSTrack.multi_gmcj   s    w<!g$FRWW\\^$FGJ!zz7*KR2==*KL"1"bqb&	A77266!5115D"1"a%A"+C
<L,M"N ,;D#xx~RaAhhsm''(89"&
(+
%, $F*Ks   !D>Er$   frame_idc                 *   || _         | j                         | _        | j                   j                  | j	                  | j
                              \  | _        | _        d| _        t        j                  | _        |dk(  rd| _        || _        || _        y)zaActivate a new tracklet using the provided Kalman filter and initialize its state and covariance.r   r
   TN)r$   next_idtrack_idinitiateconvert_coordsr#   r%   r&   r(   r   r3   r2   r'   rM   start_frame)r+   r$   rM   s      r-   activatezSTrack.activate}   s{    *%)%7%7%@%@ATATUYU_U_A`%a"	4?''
q= $D #r.   	new_tracknew_idc                    | j                   j                  | j                  | j                  | j	                  |j
                              \  | _        | _        d| _        t        j                  | _	        d| _
        || _        |r| j                         | _        |j                  | _        |j                  | _        |j                   | _        |j"                  | _        y)z`Reactivate a previously lost track using new detection data and update its state and attributes.r   TN)r$   updater%   r&   rR   tlwhr(   r   r3   r2   r'   rM   rO   rP   r   r   r*   r)   )r+   rU   rM   rV   s       r-   re_activatezSTrack.re_activate   s    %)%7%7%>%>IIt(;(;INN(K&
"	4? ''
   LLNDM__
==__
==r.   c                    || _         | xj                  dz  c_        |j                  }| j                  j	                  | j
                  | j                  | j                  |            \  | _        | _        t        j                  | _
        d| _        |j                  | _        |j                  | _        |j                  | _        |j                  | _        y)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)rM   r(   rY   r$   rX   r%   r&   rR   r   r3   r2   r'   r   r   r*   r)   )r+   rU   rM   new_tlwhs       r-   rX   zSTrack.update   s     !Q>>%)%7%7%>%>IIt(;(;H(E&
"	4?  ''
 __
==__
==r.   rY   returnc                 $    | j                  |      S )zZConvert a bounding box's top-left-width-height format to its x-y-aspect-height equivalent.)tlwh_to_xyah)r+   rY   s     r-   rR   zSTrack.convert_coords   s      &&r.   c                     | j                   | j                  j                         S | j                   dd j                         }|dxx   |d   z  cc<   |ddxxx |dd dz  z  ccc |S )zUGet the bounding box in top-left-width-height format from the current state estimate.Nr   r   rA   )r%   r#   r1   r+   rets     r-   rY   zSTrack.tlwh   sh     99::??$$iim  "A#a&BQ3qr7Q;
r.   c                 \    | j                   j                         }|ddxxx |dd z  ccc |S )ziConvert bounding box from (top left x, top left y, width, height) to (min x, min y, max x, max y) format.r   N)rY   r1   ra   s     r-   xyxyzSTrack.xyxy   s/     iinnAB3r7
r.   c                     t        j                  |       j                         }|ddxxx |dd dz  z  ccc |dxx   |d   z  cc<   |S )zWConvert bounding box from tlwh format to center-x-center-y-aspect-height (xyah) format.Nr   rA   )r    r!   r1   )rY   rb   s     r-   r_   zSTrack.tlwh_to_xyah   sL     jj##%BQ3qr7Q;A#a&
r.   c                     t        j                  | j                        j                         }|ddxxx |dd dz  z  ccc |S )z[Get the current position of the bounding box in (center x, center y, width, height) format.Nr   )r    r!   rY   r1   ra   s     r-   r   zSTrack.xywh   s>     jj#((*BQ3qr7Q;
r.   c                     | j                   !t        j                  d       | j                  S t	        j
                  | j                  | j                   d   g      S )z_Get position in (center x, center y, width, height, angle) format, warning if angle is missing.Nz1`angle` attr not found, returning `xywh` instead.)r*   r   warningr   r    concatenater+   s    r-   xywhazSTrack.xywha   sF     ::NNNO99~~tyy$**T*:;<<r.   c                     | j                   | j                  n| j                  }|j                         | j                  | j
                  | j                  | j                  gz   S )zHGet the current tracking results in the appropriate bounding box format.)r*   rd   rk   tolistrP   r   r   r)   )r+   coordss     r-   resultzSTrack.result   sF     #jj0djj}}$--TXXtxx!PPPr.   c                 V    d| j                    d| j                   d| j                   dS )zcReturn a string representation of the STrack object including start frame, end frame, and track ID.OT_z_(-))rP   rS   	end_framerj   s    r-   __repr__zSTrack.__repr__   s-    T]]O2d&6&6%7q8HJJr.   )F)!__name__
__module____qualname____doc__r   r9   r   rF   r   r   r4   staticmethodr:   r    rE   ndarrayrL   intrT   boolrZ   rX   rR   propertyrY   rd   r_   r   rk   ro   strru   __classcell__)r,   s   @r-   r   r      s   #J %&M9T%[ 9 9S 9<] (tH~ ( ( ;A266!Q< ,4> ,bjj , ,$$&6 $# $!X ! !d ! ! !C !:'2:: '"** ' bjj   bjj   2:: "**   bjj   =rzz = = QU Q Q
K# Kr.   r   c                       e Zd ZdZddefdZddeej                     deej                     dej                  fdZ	de
fd	Z	 dd
ej                  dej                  dej                  deej                     dee   f
dZdee   dee   dej                  fdZdee   fdZed        Zd Zedee   dee   dee   fd       Zedee   dee   dee   fd       Zedee   dee   deee   ee   f   fd       Zy)BYTETrackera  
    BYTETracker: A tracking algorithm built on top of YOLOv8 for object detection and tracking.

    This class encapsulates the functionality 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: Update object tracker with new detections.
        get_kalmanfilter: Return a Kalman filter object for tracking bounding boxes.
        init_track: Initialize object tracking with detections.
        get_dists: Calculate the distance between tracks and detections.
        multi_predict: Predict the location of tracks.
        reset_id: Reset the ID counter of STrack.
        reset: Reset the tracker by clearing all tracks.
        joint_stracks: Combine two lists of stracks.
        sub_stracks: Filter out the stracks present in the second list from the first list.
        remove_duplicate_stracks: Remove 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)
    
frame_ratec                     g | _         g | _        g | _        d| _        || _        t        |dz  |j                  z        | _        | j                         | _	        | j                          y)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_stracksrM   argsr|   track_buffermax_time_lostget_kalmanfilterr$   reset_id)r+   r   r   s      r-   r   zBYTETracker.__init__  sa      "!	 d!2T5F5F!FG!224r.   Nimgfeatsr]   c                    | xj                   dz  c_         g }g }g }g }|j                  }t        |d      r|j                  n|j                  }	t        j                  |	t        j                  t        |	            j                  dd      gd      }	|j                  }
|| j                  j                  k\  }|| j                  j                  kD  }|| j                  j                  k  }||z  }|	|   }|	|   }||   }||   }|
|   }|
|   }| j                  |||||n|      }g }g }| j                  D ]1  }|j                   s|j#                  |       !|j#                  |       3 | j%                  || j&                        }| j)                  |       t        | d      rK|I	 | j*                  j-                  ||      }t2        j5                  ||       t2        j5                  ||       | j7                  ||      }t9        j:                  || j                  j<                  	      \  }}}|D ]  \  }} ||   }||    }!|j>                  t@        jB                  k(  r.|jE                  |!| j                          |j#                  |       [|jG                  |!| j                   d
       |j#                  |        | j                  |||||n|      }"|D #cg c](  }#||#   j>                  t@        jB                  k(  s$||#   * }$}#t9        jH                  |$|"      }t9        j:                  |d	      \  }}}%|D ]  \  }} |$|   }|"|    }!|j>                  t@        jB                  k(  r.|jE                  |!| j                          |j#                  |       [|jG                  |!| j                   d
       |j#                  |        |D ]F  }&|$|&   }|j>                  t@        jJ                  k7  s&|jM                          |j#                  |       H |D #cg c]  }#||#   	 }}#| j7                  ||      }t9        j:                  |d	      \  }}'}|D ];  \  }} ||   jE                  ||    | j                          |j#                  ||          = |'D ](  }&||&   }|jO                          |j#                  |       * |D ]b  }(||(   }|jP                  | j                  jR                  k  r,|jU                  | jV                  | j                          |j#                  |       d | j&                  D ]J  }| j                   |jX                  z
  | jZ                  kD  s*|jO                          |j#                  |       L | j                  D )cg c]"  })|)j>                  t@        jB                  k(  s!|)$ c})| _        | j%                  | j                  |      | _        | j%                  | j                  |      | _        | j]                  | j&                  | j                        | _        | j&                  j_                  |       | j]                  | j&                  | j`                        | _        | jc                  | j                  | j&                        \  | _        | _        | j`                  j_                  |       t        | j`                        dkD  r| j`                  dd | _0        t        jd                  | j                  D *cg c]  }*|*j                   s|*jf                   c}*t
        jh                        S # t.        $ r t        j0                  dd      }Y w xY wc c}#w c c}#w c c})w c c}*w )zVUpdate the tracker with new detections and return the current list of tracked objects.r
   xywhrr   )axisNgmcr   rA   )threshF)rV   g      ?gffffff?i  ir   )5rM   confhasattrr   r   r    ri   aranger   reshaper   r   track_high_threshtrack_low_thresh
init_trackr   r'   appendjoint_stracksr   r:   r   apply	ExceptionrE   r   rL   	get_distsr   linear_assignmentmatch_threshr2   r   r3   rX   rZ   iou_distanceLost	mark_lostmark_removedr   new_track_threshrT   r$   rt   r   sub_stracksextendr   remove_duplicate_stracksr!   ro   r"   )+r+   resultsr   r   activated_stracksrefind_stracksr   r   scoresbboxesr   remain_indsinds_low	inds_highinds_seconddets_seconddetsscores_keepscores_secondcls_keep
cls_second
detectionsunconfirmedr   trackstrack_poolwarpdistsmatchesu_tracku_detectionitrackedidetdetdetections_secondr?   r_tracked_stracksu_detection_seconditu_unconfirmedinewrK   xs+                                              r-   rX   zBYTETracker.update)  s   ")'7";3v;)?)G)GA)N OVXYkk		 ; ;;DII666TYY888	*[)k"[){+{#%
__T;#\ab
)) 	.E%%""5)&&u-		. (($:K:KL;'4CO$xx~~c40 [$/[$/{J7(0(B(B5QUQZQZQgQg(h%+% 	-NHd)ET"C{{j000S$--0!((/!!#t}}U!C%%e,	- !OOK
[`[hTWnst5<kA@T@TXbXjXj@j[^kk%%&79JK/7/I/I%X[/\,,% 	-NHd%h/E#D)C{{j000S$--0!((/!!#t}}U!C%%e,	-  	+B%b)E{{joo-!##E*		+ .99jm9
9{J7.6.H.HWZ.[+% 	<NHd!((D)94==I$$[%:;	<   	*BOE ""5)	*
   	,Dt$E{{TYY777NN4--t}}=$$U+	, && 	.E}}u.1C1CC""$&&u-	.
 ,0+?+?aa177jN`N`C`a#11$2F2FHYZ#11$2F2FW ,,T->->@T@TU  . ,,T->->@T@TU262O2OPTPdPdfjfwfw2x/d/##O4t##$t+#'#7#7#>D zzT-A-ATQ^^188T\^\f\fggS  $vva|$& l( :.  b Us<   %\; %]!>]!]&"]+.]+]0]0;]]c                     t               S )zQReturn a Kalman filter object for tracking bounding boxes using KalmanFilterXYAH.r   rj   s    r-   r   zBYTETracker.get_kalmanfilter  s    !!r.   r   r   r   c           
          t        |      r.t        |||      D cg c]  \  }}}t        |||       c}}}S g S c c}}}w )zfInitialize object tracking with given detections, scores, and class labels using the STrack algorithm.)r   r;   r   )r+   r   r   r   r   rd   scs           r-   r   zBYTETracker.init_track  sC     SVVZR[s47MNN|atQ"NcaccNs   <tracksr   c                     t        j                  ||      }| j                  j                  rt        j                  ||      }|S )zZCalculate the distance between tracks and detections using IoU and optionally fuse scores.)r   r   r   
fuse_score)r+   r   r   r   s       r-   r   zBYTETracker.get_dists  s8    %%fj999''z:Er.   c                 .    t         j                  |       y)z@Predict the next states for multiple tracks using Kalman filter.N)r   r:   )r+   r   s     r-   r:   zBYTETracker.multi_predict  s    V$r.   c                  ,    t         j                          y)z^Reset the ID counter for STrack instances to ensure unique track IDs across tracking sessions.N)r   r    r.   r-   r   zBYTETracker.reset_id  s     	r.   c                     g | _         g | _        g | _        d| _        | j	                         | _        | j                          y)ziReset the tracker by clearing all tracked, lost, and removed tracks and reinitializing the Kalman filter.r   N)r   r   r   rM   r   r$   r   rj   s    r-   resetzBYTETracker.reset  s;    !!!224r.   tlistatlistbc                     i }g }| D ]"  }d||j                   <   |j                  |       $ |D ]7  }|j                   }|j                  |d      r"d||<   |j                  |       9 |S )zbCombine two lists of STrack objects into a single list, ensuring no duplicates based on track IDs.r
   r   )rP   r   get)r   r   existsresrK   tids         r-   r   zBYTETracker.joint_stracks  sy      	A!"F1::JJqM	  	A**C::c1%s

1		
 
r.   c                     |D ch c]  }|j                    }}| D cg c]  }|j                   |vs| c}S c c}w c c}w )zFFilter out the stracks present in the second list from the first list.)rP   )r   r   rK   track_ids_bs       r-   r   zBYTETracker.sub_stracks  s?     ,22aqzz22!CaQZZ{%BCC 3Cs   9>>stracksastracksbc                    t        j                  | |      }t        j                  |dk        }g g }}t	        | D ]k  \  }}| |   j
                  | |   j                  z
  }||   j
                  ||   j                  z
  }	||	kD  r|j                  |       [|j                  |       m t        |       D 
cg c]  \  }
}|
|vs| }}
}t        |      D 
cg c]  \  }
}|
|vs| }}
}||fS c c}}
w c c}}
w )zXRemove duplicate stracks from two lists based on Intersection over Union (IoU) distance.g333333?)	r   r   r    wherer;   rM   rS   r   r8   )r   r   pdistpairsdupadupbpqtimeptimeqr?   rK   resaresbs                 r-   r   z$BYTETracker.remove_duplicate_stracks  s     %%h9&dK 	DAqQK((8A;+B+BBEQK((8A;+B+BBEu}AA	 (1CdaQd]CC'1CdaQd]CCTz DCs   7C1C1C7&C7)   r   )N)rv   rw   rx   ry   r|   r   r   r    r{   rX   r   r   r   r   r   r   r:   rz   r   r   r   r   r   r   r   r.   r-   r   r      s   !F .th8BJJ#7 thxPRPZPZG[ thgigqgq thl""2 "
 bfdJJd(*

d9;dJRSUS]S]J^d	fdV $v, 2:: %DL %   d6l DL T&\   DDL D$v, D4< D D
 4< 4< TYZ^_eZfhlmshtZtTu  r.   r   )typingr   r   r   r   numpyr    utilsr   	utils.opsr	   	basetrackr   r   r   utils.kalman_filterr   r   r   r   r.   r-   <module>r      s<    . -   ! ,  1]KY ]K@x xr.   