o
    Wh<'                     @   s4   d dl mZmZmZ d dlmZ G dd deZdS )    )BaseSolutionSolutionAnnotatorSolutionResults)colorsc                       s@   e Zd ZdZ fddZdd Zdd Zdd	 Zd
d Z  Z	S )ObjectCountera  
    A class to manage the counting of objects in a real-time video stream based on their tracks.

    This class extends the BaseSolution class and provides functionality for counting objects moving in and out of a
    specified region in a video stream. It supports both polygonal and linear regions for counting.

    Attributes:
        in_count (int): Counter for objects moving inward.
        out_count (int): Counter for objects moving outward.
        counted_ids (List[int]): List of IDs of objects that have been counted.
        classwise_counts (Dict[str, Dict[str, int]]): Dictionary for counts, categorized by object class.
        region_initialized (bool): Flag indicating whether the counting region has been initialized.
        show_in (bool): Flag to control display of inward count.
        show_out (bool): Flag to control display of outward count.

    Methods:
        count_objects: Counts objects within a polygonal or linear region.
        store_classwise_counts: Initializes class-wise counts if not already present.
        display_counts: Displays object counts on the frame.
        process: Processes input data (frames or object tracks) and updates counts.

    Examples:
        >>> counter = ObjectCounter()
        >>> frame = cv2.imread("frame.jpg")
        >>> results = counter.process(frame)
        >>> print(f"Inward count: {counter.in_count}, Outward count: {counter.out_count}")
    c                    sX   t  jdi | d| _d| _g | _i | _d| _| jd | _| jd | _	| j
d | _dS )zSInitializes the ObjectCounter class for real-time object counting in video streams.r   Fshow_inshow_out   N )super__init__in_count	out_countcounted_idsclasswise_countsregion_initializedCFGr   r   
line_widthmargin)selfkwargs	__class__r
   X/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/solutions/object_counter.pyr   $   s   zObjectCounter.__init__c           	      C   s  |du s	|| j v rdS t| jdkr| | j}|| ||grt| jd d | jd d  t| jd d | jd d  k rv|d |d kr`|  jd7  _| j| j|  d  d7  < nI|  j	d7  _	| j| j|  d  d7  < n3|d |d kr|  jd7  _| j| j|  d  d7  < n|  j	d7  _	| j| j|  d  d7  < | j 
| dS dS t| jdkr@| | j}|| |rBtdd | jD tdd | jD  }td	d | jD td	d | jD  }||k r|d |d ks||kr#|d |d kr#|  jd7  _| j| j|  d  d7  < n|  j	d7  _	| j| j|  d  d7  < | j 
| dS dS dS )
ap  
        Counts objects within a polygonal or linear region based on their tracks.

        Args:
            current_centroid (Tuple[float, float]): Current centroid coordinates (x, y) in the current frame.
            track_id (int): Unique identifier for the tracked object.
            prev_position (Tuple[float, float]): Last frame position coordinates (x, y) of the track.
            cls (int): Class index for classwise count updates.

        Examples:
            >>> counter = ObjectCounter()
            >>> track_line = {1: [100, 200], 2: [110, 210], 3: [120, 220]}
            >>> box = [130, 230, 150, 250]
            >>> track_id_num = 1
            >>> previous_position = (120, 220)
            >>> class_to_count = 0  # In COCO model, class 0 = person
            >>> counter.count_objects((140, 240), track_id_num, previous_position, class_to_count)
        Nr	   r      INOUTc                 s       | ]}|d  V  qdS )r   Nr
   .0pr
   r
   r   	<genexpr>a       z.ObjectCounter.count_objects.<locals>.<genexpr>c                 s   r   )r   Nr
   r   r
   r
   r   r!   b   r"   )r   lenregion
LineString
intersectsabsr   r   namesr   appendPolygoncontainsPointmaxmin)	r   current_centroidtrack_idprev_positionclslinepolygonregion_widthregion_heightr
   r
   r   count_objects2   sD   @((
zObjectCounter.count_objectsc                 C   s.   | j | | jvrddd| j| j | < dS dS )a  
        Initialize class-wise counts for a specific object class if not already present.

        Args:
            cls (int): Class index for classwise count updates.

        Examples:
            >>> counter = ObjectCounter()
            >>> counter.store_classwise_counts(0)  # Initialize counts for class index 0
            >>> print(counter.classwise_counts)
            {'person': {'IN': 0, 'OUT': 0}}
        r   )r   r   N)r(   r   )r   r2   r
   r
   r   store_classwise_countsq   s   z$ObjectCounter.store_classwise_countsc                    s:    fdd j  D }|r j||dd j dS dS )a<  
        Display object counts on the input image or frame.

        Args:
            plot_im (numpy.ndarray): The image or frame to display counts on.

        Examples:
            >>> counter = ObjectCounter()
            >>> frame = cv2.imread("image.jpg")
            >>> counter.display_counts(frame)
        c              	      sn   i | ]3\}}|d  dks|d dkrt | jr!dt |d   nd d jr/dt |d  nd  qS )r   r   r   zIN   zOUT )str
capitalizer   r   strip)r   keyvaluer   r
   r   
<dictcomp>   s    $z0ObjectCounter.display_counts.<locals>.<dictcomp>)h         )   rE   rE   N)r   items	annotatordisplay_analyticsr   )r   plot_imlabels_dictr
   r@   r   display_counts   s   
zObjectCounter.display_countsc           	      C   s<  | j s
|   d| _ | | t|| jd| _| jj| jd| jd d t| j	| j
| j| jD ]P\}}}}| jj|| |||t|dd | || | | |d |d  d |d |d	  d f}d
}t| j| dkrw| j| d }| |||| q/| j }| | | | t|| j| j| jt| j
dS )a[  
        Process input data (frames or object tracks) and update object counts.

        This method initializes the counting region, extracts tracks, draws bounding boxes and regions, updates
        object counts, and displays the results on the input image.

        Args:
            im0 (numpy.ndarray): The input image or frame to be processed.

        Returns:
            (SolutionResults): Contains processed image `im0`, 'in_count' (int, count of objects entering the region),
                'out_count' (int, count of objects exiting the region), 'classwise_count' (dict, per-class object count),
                and 'total_tracks' (int, total number of tracked objects).

        Examples:
            >>> counter = ObjectCounter()
            >>> frame = cv2.imread("path/to/image.jpg")
            >>> results = counter.process(frame)
        T)r   )rB   r   {   r	   )reg_ptscolor	thickness)labelrN   r   r      N)rI   r   r   classwise_counttotal_tracks)r   initialize_regionextract_tracksr   r   rG   draw_regionr$   zipboxes	track_idsclssconfs	box_labeladjust_box_labelr   store_tracking_historyr8   r#   track_historyr7   resultrK   display_outputr   r   r   r   )	r   im0boxr0   r2   confr/   r1   rI   r
   r
   r   process   s6   
""
(


zObjectCounter.process)
__name__
__module____qualname____doc__r   r7   r8   rK   rf   __classcell__r
   r
   r   r   r      s    ?r   N)ultralytics.solutions.solutionsr   r   r   ultralytics.utils.plottingr   r   r
   r
   r
   r   <module>   s   