
    |h                     Z    d dl mZ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)    )AnyDictListTupleN)BaseSolutionSolutionAnnotatorSolutionResults)colorsc                        e Zd ZdZdeddf fdZdedee   dee	e	e	f   d	ee	e	e	f   de
eef   f
d
Zd Zdej                  defdZ x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: Add a new counting region with specified attributes.
        process: Process video frames to count objects in each region.
        initialize_regions: Initialize zones to count the objects in each one. Zones could be multiple as well.

    Examples:
        Initialize a RegionCounter and add a counting region
        >>> counter = RegionCounter()
        >>> counter.add_region("Zone1", [(100, 100), (200, 100), (200, 200), (100, 200)], (255, 0, 0), (255, 255, 255))
        >>> results = counter.process(frame)
        >>> print(f"Total tracks: {results.total_tracks}")
    kwargsreturnNc                 z    t        |   di | dddddd| _        i | _        g | _        | j                          y)zSInitialize the RegionCounter for real-time object counting in user-defined regions.zDefault RegionNr      r   r   )r   r   r   )namepolygoncountsregion_color
text_color )super__init__region_templateregion_countscounting_regionsinitialize_regions)selfr   	__class__s     c/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/solutions/region_counter.pyr   zRegionCounter.__init__'   sJ    "6"$+# 
   "!    r   polygon_pointsr   r   c                     | j                   j                         }|j                  || j                  |      ||d       | j                  j                  |       |S )aM  
        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[int, int, int]): BGR color for region visualization.
            text_color (Tuple[int, int, int]): BGR color for the text within the region.

        Returns:
            (Dict[str, any]): Returns a dictionary including the region information i.e. name, region_color etc.
        )r   r   r   r   )r   copyupdatePolygonr   append)r   r   r"   r   r   regions         r    
add_regionzRegionCounter.add_region5   sY    & %%**,<<7 ,(		
 	$$V,r!   c           	      \   | j                   | j                          t        | j                   t              sd| j                   i| _         t	        | j                   j                               D ]=  \  }\  }}| j                  ||t        |d      d      }| j                  |d         |d<   ? y)zInitialize regions only once.Nz	Region#01Tr   r   prepared_polygon)	r(   initialize_region
isinstancedict	enumerateitemsr)   r
   prep)r   ir   ptsr(   s        r    r   z RegionCounter.initialize_regionsT   s    ;;""$$++t,&4DK'(9(9(;< 	FNA{c__T3q$QF)-6)3D)EF%&	Fr!   im0c           	         | j                  |       t        || j                        }t        | j                  | j
                  | j                  | j                        D ]  \  }}}}|j                  || j                  |||      t        |d             | j                  |d   |d   z   dz  |d   |d   z   dz  f      }| j                  D ]9  }|d   j                  |      s|d	xx   dz  cc<   |d	   | j                  |d
   <   ;  | j                  D ]  }t        t         |d   j"                        \  }	}
}}|	|
f||
f||f|	|fg}|j%                  ||d   | j                  dz         |j'                  |	|
||gt)        |d	         |d   |d   | j                  dz         d|d	<    |j+                         }| j-                  |       t/        |t1        | j                        | j                        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_widthT)labelcolorr            r+   r   r   r   r   r      )r7   r8   	txt_colormargin)plot_imtotal_tracksr   )extract_tracksr   r6   zipboxesclss	track_idsconfs	box_labeladjust_box_labelr
   Pointr   containsr   mapintboundsdraw_region
text_labelstrresultdisplay_outputr	   len)r   r4   	annotatorboxclstrack_idconfcenterr(   x1y1x2y2r3   r?   s                  r    processzRegionCounter.process^   s    	C %cdooF	(+DJJ		4>>SWS]S](^ 	J$Ch4+@+@dH+U]cdlnr]stZZ#a&3q6/Q!6Q#a&A8M NOF// J,-66v>8$)$9?9ID&&vf~6J	J ++ 	!F fY&7&>&>?NBB8b"XBx"b:C!!#vn'=tQR?RS  RR &*+^, .* !   !F8	! ""$G$wS=P`d`r`rssr!   )__name__
__module____qualname____doc__r   r   rP   r   r   rL   r   r)   r   npndarrayr	   r^   __classcell__)r   s   @r    r   r      s    6" " " U CcM*	
 #sC-( 
c3h>F&t2:: &t/ &tr!   r   )typingr   r   r   r   numpyrc   ultralytics.solutions.solutionsr   r   r	   ultralytics.utils.plottingr
   r   r   r!   r    <module>rj      s)    * )  \ \ -ytL ytr!   