o
    Wh*                     @   s<   d dl Zd dlmZmZmZ d dlmZ G dd deZdS )    N)BaseSolutionSolutionAnnotatorSolutionResults)colorsc                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )RegionCountera  
    A class for real-time counting of objects within user-defined regions in a video stream.

    This class inherits from `BaseSolution` and provides functionality to define polygonal regions in a video frame,
    track objects, and count those objects that pass through each defined region. Useful for applications requiring
    counting in specified areas, such as monitoring zones or segmented sections.

    Attributes:
        region_template (dict): Template for creating new counting regions with default attributes including name,
            polygon coordinates, and display colors.
        counting_regions (list): List storing all defined regions, where each entry is based on `region_template`
            and includes specific region settings like name, coordinates, and color.
        region_counts (dict): Dictionary storing the count of objects for each named region.

    Methods:
        add_region: Adds a new counting region with specified attributes.
        process: Processes video frames to count objects in each region.
    c                    s6   t  jdi | ddddddd| _i | _g | _dS )	zaInitializes the RegionCounter class for real-time counting in different regions of video streams.zDefault RegionNr   F)   r   r   )r   r   r   )namepolygoncountsdraggingregion_color
text_color )super__init__region_templateregion_countscounting_regions)selfkwargs	__class__r   X/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/solutions/region_counter.pyr      s   
zRegionCounter.__init__c                 C   s4   | j  }||| |||d | j| dS )a  
        Add a new region to the counting list based on the provided template with specific attributes.

        Args:
            name (str): Name assigned to the new region.
            polygon_points (List[Tuple]): List of (x, y) coordinates defining the region's polygon.
            region_color (tuple): BGR color for region visualization.
            text_color (tuple): BGR color for the text within the region.
        )r   r	   r   r   N)r   copyupdatePolygonr   append)r   r   polygon_pointsr   r   regionr   r   r   
add_region+   s   

zRegionCounter.add_regionc                    s    | t| jd}t jtsd jp  i _t j ddD ]\}\}}t	|d}|
|| jd   ||||  q% jD ]}d|vrW |d |d< qHtjd	d
  jD tjd} fdd
|D }	|	rt|	 j j j jD ]5\}
}}}}|j| |||t	|dd  jD ]}|d |
r|d  d7  < |d  j|d < qq} jD ]}|j|d jt|d |d |d  jd d d|d< q| } | t |t! j jdS )a  
        Process the input frame to detect and count objects within each defined region.

        Args:
            im0 (np.ndarray): Input image frame where objects and regions are annotated.

        Returns:
            (SolutionResults): Contains processed image `plot_im`, 'total_tracks' (int, total number of tracked objects),
                and 'region_counts' (dict, counts of objects per region).
        )
line_widthz	Region#01   )startT   prepared_polygonr	   c                 S   s4   g | ]}|d  |d  d |d |d  d fqS )r   r#   r!      r   ).0boxr   r   r   
<listcomp>^   s   4 z)RegionCounter.process.<locals>.<listcomp>)dtypec                    s   g | ]}  |qS r   )Point)r&   ptr   r   r   r(   _   s    )labelcolorr
   r   r   r      )r-   r.   	txt_colormarginr   )plot_imtotal_tracksr   )"extract_tracksr   r    
isinstancer   dictinitialize_region	enumerateitemsr   draw_regionr   get_txt_colorr   prepnparrayboxesfloat32zipclss	track_idsconfs	box_labeladjust_box_labelcontainsr   
text_labelboundsstrresultdisplay_outputr   len)r   im0	annotatoridxregion_namereg_ptsr.   r   boxes_nppointspointclstrack_idr'   confr2   r   r,   r   process@   sF   


& 




zRegionCounter.process)__name__
__module____qualname____doc__r   r   rY   __classcell__r   r   r   r   r   	   s
    r   )	numpyr=   ultralytics.solutions.solutionsr   r   r   ultralytics.utils.plottingr   r   r   r   r   r   <module>   s   