
    j                     ^    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
dS )    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                 d     t                      j        di | d| _        i | _        g | _        dS )zYInitialize the DistanceCalculation class for measuring object distances in video streams.r   N )super__init__left_mouse_countselected_boxes	centroids)selfr
   	__class__s     o/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/solutions/distance_calculation.pyr   zDistanceCalculation.__init__#   s=    ""6""" !"68*,    eventxyflagsparamc                 z   |t           j        k    r| xj        dz  c_        | j        dk    rkt          | j        | j                  D ]R\  }}|d         |cxk     r|d         k     r2n !|d         |cxk     r|d         k     rn =|| j        vr
|| j        |<   QdS dS |t           j        k    ri | _        d| _        dS dS )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%D < <MC1v****CF*****s1v/B/B/B/BCF/B/B/B/B/BxW[WjGjGj8;+H5 *)< < c+++"$D$%D!!! ,+r   c           
         |                      |           t          || j                  }d}t          | j        | j        | j        | j                  D ]\  }}}}|                    |t          t          |          d          |                     |||                     t          | j                  dk    r,| j                                        D ]}||k    r
|| j        |<   t          | j                  dk    r| j                            d | j                                        D                        t%          j        | j        d         d         | j        d         d         z
  dz  | j        d         d         | j        d         d         z
  dz  z             }|                    || j                   g | _        |                                }	|                     |	           | j                            d          r!| j        rt5          j        d	| j                   t;          |	|t          | j                  
          S )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   c                     g | ]D}t          |d          |d         z   dz            t          |d         |d         z   dz            gES )r   r   r   r   )int).0r&   s     r   
<listcomp>z/DistanceCalculation.process.<locals>.<listcomp>l   sP    tttPS#s1vA1,--sCFSVO3I/J/JKtttr   r   showzUltralytics Solutions)plot_impixels_distancetotal_tracks)extract_tracksr   r*   r"   r#   r$   clssconfs	box_labelr   r.   adjust_box_labellenr   keysr   extendvaluesmathsqrtplot_distance_and_lineresultdisplay_outputCFGget	env_checkr    setMouseCallbackr(   r   )
r   im0	annotatorr3   r&   r'   clsconftrk_idr2   s
             r   processzDistanceCalculation.processE   sJ   , 	C   %cdoFFF	(+DJ	SWS](^(^ 	< 	<$C36#c((D+A+AI^I^_bdhjrIsIsttt 4&''1,,"16688 < <F))8;+H5t"##q((N!!ttW[WjWqWqWsWsttt   #i"1%q(9!(<<BdnUVFWXYFZ]a]klm]nop]qFqvwEww O ,,_dnMMM""$$G$$$8<< 	YDN 	Y !8$:WXXX w^abfbp^q^qrrrrr   )__name__
__module____qualname____doc__r   r   r.   r(   r   rL   __classcell__)r   s   @r   r	   r	      s         ,- - - - - - - -&c &c &c &# &VY &^b & & & &26so 6s 6s 6s 6s 6s 6s 6s 6sr   r	   )r>   typingr   r    ultralytics.solutions.solutionsr   r   r   ultralytics.utils.plottingr   r	   r   r   r   <module>rU      s           



 \ \ \ \ \ \ \ \ \ \ - - - - - -os os os os os, os os os os osr   