
    |h3                     ^    d dl Z d dlmZmZ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DictList)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, List[float]]): Dictionary to store selected bounding boxes and their track IDs.
        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     i/var/www/html/test/engine/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 <MC1v*CF*s1v/BCF/BxW[WjWjGj8;++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 (numpy.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	annotatorr1   r(   r)   clsconftrk_idr0   s
             r   processzDistanceCalculation.processG   sF   . 	C %cdooF	(+DJJ		SWS]S](^ 	<$C36#c(D+AI^I^_bdhjrIst 4&&'1,"11668 <F)8;++H5<	< t""#q(NN!!W[WjWjWqWqWstPS#s1vA1,-sCFSVO3I/JKt #ii"1%q(9!(<<BdnnUVFWXYFZ]a]k]klm]nop]qFqvwEwwO ,,_dnnM""$G$88<<DNN  !8$:W:WX w^abfbpbp^qrr us   95J)__name__
__module____qualname____doc__r   r   r7   r*   r   rK   __classcell__)r   s   @r   r   r      sZ    .- - -&c &c &c &# &VY &^b &47so 7sr   r   )r=   typingr   r   r   r"   ultralytics.solutions.solutionsr   r   r   ultralytics.utils.plottingr	   r   r   r   r   <module>rT      s,     " " 
 \ \ -rs, rsr   