Ë
    Fêñi  ã                   óV   — d dl Z d dlmZ d dlZd dlmZmZmZ d dlm	Z	  G d„ de«      Z
y)é    N)ÚAny)ÚBaseSolutionÚSolutionAnnotatorÚSolutionResults)Úcolorsc                   óX   ‡ — e Zd ZdZdeddfˆ fd„Zdededed	ed
eddfd„Zdefd„Z	ˆ xZ
S )ÚDistanceCalculationa  A class to calculate distance between two objects in a real-time video stream based on their tracks.

    This class extends BaseSolution to provide functionality for selecting objects and calculating the distance between
    them in a video stream using YOLO object detection and tracking.

    Attributes:
        left_mouse_count (int): Counter for left mouse button clicks.
        selected_boxes (dict[int, Any]): Dictionary to store selected bounding boxes keyed by track ID.
        centroids (list[list[int]]): List to store centroids of selected bounding boxes.

    Methods:
        mouse_event_for_distance: Handle mouse events for selecting objects in the video stream.
        process: Process video frames and calculate the distance between selected objects.

    Examples:
        >>> distance_calc = DistanceCalculation()
        >>> frame = cv2.imread("frame.jpg")
        >>> results = distance_calc.process(frame)
        >>> cv2.imshow("Distance Calculation", results.plot_im)
        >>> cv2.waitKey(0)
    ÚkwargsÚreturnNc                 óN   •— t        ‰| �  di |¤Ž d| _        i | _        g | _        y)zYInitialize the DistanceCalculation class for measuring object distances in video streams.r   N© )ÚsuperÚ__init__Úleft_mouse_countÚselected_boxesÚ	centroids)Úselfr
   Ú	__class__s     €úl/var/www/pod-logistic/pod-ai/venv/lib/python3.12/site-packages/ultralytics/solutions/distance_calculation.pyr   zDistanceCalculation.__init__#   s,   ø€ ä‰ÑÑ"˜6Ò"ð !"ˆÔØ68ˆÔØ*,ˆ�ó    ÚeventÚxÚyÚflagsÚparamc                 óš  — |t         j                  k(  r–| xj                  dz  c_        | j                  dk  rqt        | j                  | j
                  «      D ]M  \  }}|d   |cxk  r	|d   k  sŒn Œ|d   |cxk  r	|d   k  sŒ-n Œ0|| j                  vsŒ?|| j                  |<   ŒO yy|t         j                  k(  ri | _        d| _        yy)a§  Handle mouse events to select regions in a real-time video stream for distance calculation.

        Args:
            event (int): Type of mouse event (e.g., cv2.EVENT_MOUSEMOVE, cv2.EVENT_LBUTTONDOWN).
            x (int): X-coordinate of the mouse pointer.
            y (int): Y-coordinate of the mouse pointer.
            flags (int): Flags associated with the event (e.g., cv2.EVENT_FLAG_CTRLKEY, cv2.EVENT_FLAG_SHIFTKEY).
            param (Any): Additional parameters passed to the function.

        Examples:
            >>> # Assuming 'dc' is an instance of DistanceCalculation
            >>> cv2.setMouseCallback("window_name", dc.mouse_event_for_distance)
        é   é   r   é   N)Úcv2ÚEVENT_LBUTTONDOWNr   ÚzipÚboxesÚ	track_idsr   ÚEVENT_RBUTTONDOWN)r   r   r   r   r   r   ÚboxÚtrack_ids           r   Úmouse_event_for_distancez,DistanceCalculation.mouse_event_for_distance,   sÄ   € ð ”C×)Ñ)Ò)Ø×!Ò! QÑ&Õ!Ø×$Ñ$¨Ò)Ü%(¨¯©°T·^±^Ó%Dò <‘M�C˜Ø˜1‘v Ô* C¨¡FÖ*¨s°1©v¸Ô/B¸CÀ¹FÖ/BÀxÐW[×WjÑWjÒGjØ8;˜×+Ñ+¨HÒ5ñ<ð *ð
 ”c×+Ñ+Ò+Ø"$ˆDÔØ$%ˆDÕ!ð ,r   c                 ó  — | j                  |«       t        || j                  ¬«      }d}t        | j                  | j
                  | j                  | j                  «      D ]Œ  \  }}}}|j                  |t        t        |«      d«      | j                  |||«      ¬«       t        | j                  «      dk(  sŒY| j                  j                  «       D ]  }||k(  sŒ	|| j                  |<   Œ ŒŽ t        | j                  «      dk(  rí| j                  j!                  | j                  j#                  «       D �cg c]0  }t        |d   |d   z   dz  «      t        |d   |d   z   dz  «      g‘Œ2 c}«       t%        j&                  | j                  d   d   | j                  d   d   z
  dz  | j                  d   d   | j                  d   d   z
  dz  z   «      }|j)                  || j                  «       g | _        |j+                  «       }	| j-                  |	«       | j.                  j1                  d«      r,| j2                  r t5        j6                  d	| j8                  «       t;        |	|t        | j
                  «      ¬
«      S c c}w )aç  Process a video frame and calculate the distance between two selected bounding boxes.

        This method extracts tracks from the input frame, annotates bounding boxes, and calculates the distance between
        two user-selected objects if they have been chosen.

        Args:
            im0 (np.ndarray): The input image frame to process.

        Returns:
            (SolutionResults): Contains processed image `plot_im`, `total_tracks` (int) representing the total number of
                tracked objects, and `pixels_distance` (float) representing the distance between selected objects
                in pixels.

        Examples:
            >>> import numpy as np
            >>> from ultralytics.solutions import DistanceCalculation
            >>> dc = DistanceCalculation()
            >>> frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
            >>> results = dc.process(frame)
            >>> print(f"Distance: {results.pixels_distance:.2f} pixels")
        )Ú
line_widthr   T)ÚcolorÚlabelr   r   r   ÚshowzUltralytics Solutions)Úplot_imÚpixels_distanceÚtotal_tracks)Úextract_tracksr   r*   r"   r#   r$   ÚclssÚconfsÚ	box_labelr   ÚintÚadjust_box_labelÚlenr   Úkeysr   ÚextendÚvaluesÚmathÚsqrtÚplot_distance_and_lineÚresultÚdisplay_outputÚCFGÚgetÚ	env_checkr    ÚsetMouseCallbackr(   r   )
r   Úim0Ú	annotatorr/   r&   r'   ÚclsÚconfÚtrk_idr.   s
             r   ÚprocesszDistanceCalculation.processE   sF  € ð, 	×Ñ˜CÔ Ü% c°d·o±oÔFˆ	àˆä(+¨D¯J©J¸¿¹ÈÏ	É	ÐSW×S]ÑS]Ó(^ò 	<Ñ$ˆC�˜3 Ø×Ñ ¬6´#°c³(¸DÓ+AÈ×I^ÑI^Ð_bÐdhÐjrÓIsÐÔtô �4×&Ñ&Ó'¨1Ó,Ø"×1Ñ1×6Ñ6Ó8ò <�FØ Ó)Ø8;˜×+Ñ+¨HÒ5ñ<ð	<ô ˆt×"Ñ"Ó# qÒ(à�N‰N×!Ñ!ØW[×WjÑWj×WqÑWqÓWsÖtÐPS”#�s˜1‘v  A¡‘¨1Ñ,Ó-¬s°C¸±F¸SÀ¹V±OÈÑ3IÓ/JÒKÒtôô #Ÿi™iØ—‘ Ñ" 1Ñ%¨¯©°qÑ(9¸!Ñ(<Ñ<ÀÑBÀdÇnÁnÐUVÑFWÐXYÑFZÐ]a×]kÑ]kÐlmÑ]nÐopÑ]qÑFqÐvwÑEwÑwóˆOð ×,Ñ,¨_¸d¿n¹nÔMàˆŒØ×"Ñ"Ó$ˆØ×Ñ˜GÔ$Ø�8‰8�<‰<˜Ô D§N¢NÜ× Ñ Ð!8¸$×:WÑ:WÔXô  wÀÔ^aÐbf×bpÑbpÓ^qÔrÐrùò us   Ä95J)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r5   r(   r   rI   Ú__classcell__)r   s   @r   r	   r	      sZ   ø„ ñð,- ð -¨õ -ð&¨cð &°cð &¸cð &È#ð &ÐVYð &Ð^bó &ð26s˜o÷ 6sr   r	   )r;   Útypingr   r    Úultralytics.solutions.solutionsr   r   r   Úultralytics.utils.plottingr   r	   r   r   r   ú<module>rR      s)   ðó Ý ã 
ç \Ñ \Ý -ôos˜,õ osr   