
    |h                     ^    d dl mZ d dlmZ d dlmZ d dlmZmZm	Z	 d dl
mZ  G d de      Zy)	    )deque)sqrt)Any)BaseSolutionSolutionAnnotatorSolutionResults)colorsc                   8     e Zd ZdZdeddf fdZdefdZ xZS )SpeedEstimatora  
    A class to estimate the speed of objects in a real-time video stream based on their tracks.

    This class extends the BaseSolution class and provides functionality for estimating object speeds using
    tracking data in video streams. Speed is calculated based on pixel displacement over time and converted
    to real-world units using a configurable meters-per-pixel scale factor.

    Attributes:
        fps (float): Video frame rate for time calculations.
        frame_count (int): Global frame counter for tracking temporal information.
        trk_frame_ids (dict): Maps track IDs to their first frame index.
        spd (dict): Final speed per object in km/h once locked.
        trk_hist (dict): Maps track IDs to deque of position history.
        locked_ids (set): Track IDs whose speed has been finalized.
        max_hist (int): Required frame history before computing speed.
        meter_per_pixel (float): Real-world meters represented by one pixel for scene scale conversion.
        max_speed (int): Maximum allowed object speed; values above this will be capped.

    Methods:
        process: Process input frames to estimate object speeds based on tracking data.
        store_tracking_history: Store the tracking history for an object.
        extract_tracks: Extract tracks from the current frame.
        display_output: Display the output with annotations.

    Examples:
        Initialize speed estimator and process a frame
        >>> estimator = SpeedEstimator(meter_per_pixel=0.04, max_speed=120)
        >>> frame = cv2.imread("frame.jpg")
        >>> results = estimator.process(frame)
        >>> cv2.imshow("Speed Estimation", results.plot_im)
    kwargsreturnNc                    t        |   di | | j                  d   | _        d| _        i | _        i | _        i | _        t               | _	        | j                  d   | _
        | j                  d   | _        | j                  d   | _        y)z
        Initialize the SpeedEstimator object with speed estimation parameters and data structures.

        Args:
            **kwargs (Any): Additional keyword arguments passed to the parent class.
        fpsr   max_histmeter_per_pixel	max_speedN )super__init__CFGr   frame_counttrk_frame_idsspdtrk_histset
locked_idsr   r   r   )selfr   	__class__s     e/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/solutions/speed_estimation.pyr   zSpeedEstimator.__init__,   s}     	"6"88E?%,#xx(9:+.    c           	      N   | xj                   dz  c_         | j                  |       t        || j                        }t	        | j
                  | j                  | j                  | j                        D ]  \  }}}}| j                  ||       || j                  vr<t        | j                        | j                  |<   | j                   | j                  |<   || j                  vr;| j                  |   }|j                  | j                   d          t#        |      | j                  k(  r|d   |d   }}| j                   | j                  |   z
  | j$                  z  }	|	dkD  r|d   |d   z
  |d   |d   z
  }}
t'        |
|
z  ||z  z         }|| j(                  z  }t+        t-        ||	z  dz  | j.                              | j0                  |<   | j                  j3                  |       | j                  j5                  |d       | j                  j5                  |d       || j0                  v s| j0                  |    d}|j7                  ||t9        |d	      
        |j;                         }| j=                  |       t?        |t#        | j                              S )a@  
        Process an input frame to estimate object speeds based on tracking data.

        Args:
            im0 (np.ndarray): Input image for processing with shape (H, W, C) for RGB images.

        Returns:
            (SolutionResults): Contains processed image `plot_im` and `total_tracks` (number of tracked objects).

        Examples:
            Process a frame for speed estimation
            >>> estimator = SpeedEstimator()
            >>> image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
            >>> results = estimator.process(image)
           )
line_width)maxlenr   g@Nz km/hT)labelcolor)plot_imtotal_tracks) r   extract_tracksr   r#   zipboxes	track_idsclssconfsstore_tracking_historyr   r   r   r   r   append
track_linelenr   r   r   intminr   r   addpop	box_labelr	   resultdisplay_outputr   )r   im0	annotatorboxtrack_id_r   p0p1dtdxdypixel_distancemetersspeed_labelr(   s                   r   processzSpeedEstimator.process?   sS     	AC %cdooF	#&tzz4>>499djj#Y 	ZC1a''#6t}},*/t}}*Eh'/3/?/?""8,t.==2 34 x=DMM1%a[(2,B**T-?-?-IITXXUBAv!#AA11B)-b2gR.?)@!/$2F2F!F-0" 3T^^D.* ++H5))(D9**..x>488#!%(!3 4E:##C{&SWBX#Y9	Z< ""$G$ wS=PQQr    )	__name__
__module____qualname____doc__r   r   r   rH   __classcell__)r   s   @r   r   r      s*    @/ / /&6Ro 6Rr    r   N)collectionsr   mathr   typingr   ultralytics.solutions.solutionsr   r   r   ultralytics.utils.plottingr	   r   r   r    r   <module>rS      s)       \ \ -jR\ jRr    