
    j                    b    d dl m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 )    )annotations)AnyN)BaseSolutionSolutionAnnotatorSolutionResults)colorsc                  :     e Zd ZdZd fdZddZd Zd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}")
    kwargsr   returnNonec                     t                      j        di | dddddd| _        i | _        g | _        |                                  dS )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     i/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/solutions/region_counter.pyr   zRegionCounter.__init__(   sh    ""6"""$+# 
  
   "!!!!!    r   strpolygon_pointslist[tuple]r   tuple[int, int, int]r   dict[str, Any]c                    | j                                         }|                    ||                     |          ||d           | j                            |           |S )a1  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]): Region information including name, polygon, and display colors.
        )r   r   r   r   )r   copyupdatePolygonr   append)r   r   r"   r   r   regions         r   
add_regionzRegionCounter.add_region6   sn    $ %**,,<<77 ,(	 	
 	
 	
 	$$V,,,r    c           	     r   | j         |                                  t          | j         t                    sd| j         i| _         t	          | j                                                   D ]L\  }\  }}|                     ||t          |d          d          }|                     |d                   |d<   MdS )z0Initialize regions from `self.region` 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,, 	5&4DK'(9(9(;(;<< 	F 	FNA{c__T3q$QQF)-6)3D)E)EF%&&	F 	Fr    im0
np.ndarrayr   c           
        |                      |           t          || j                  }t          | j        | j        | j        | j                  D ]\  }}}}|                    || 	                    |||          t          |d                     |                     |d         |d         z   dz  |d         |d         z   dz  f          }| j        D ]C}|d                             |          r&|d	xx         dz  cc<   |d	         | j        |d
         <   D| j        D ]}|d         }	t          t!          t"          t%          j        |	j        j        t$          j                                      }
t/          |	j        j                  t/          |	j        j                  fgdz  \  \  }}\  }}|                    |
|d         | j        dz             |                    ||||gt;          |d	                   |d         |d         | j        dz  d           d|d	<   |                                }|                     |           tA          |tC          | 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   )dtyper   r      rect)r;   r<   	txt_colormarginshape)plot_imtotal_tracksr   )"extract_tracksr   r:   zipboxesclss	track_idsconfs	box_labeladjust_box_labelr   Pointr   containsr   listmaptuplenparrayexteriorcoordsint32intcentroidxydraw_regionadaptive_labelr!   resultdisplay_outputr   len)r   r7   	annotatorboxclstrack_idconfcenterr+   polyr6   x1y1x2y2rF   s                   r   processzRegionCounter.process^   s    	C   %cdoFFF	(+DJ	4>SWS](^(^ 	J 	J$Ch4+@+@dH+U+U]cdlnr]s]stttZZ#a&3q6/Q!6Q#a&A8M NOOF/ J J,-66v>> J8$$$)$$$9?9ID&vf~6J + 	! 	!F)$Ds5"(4=+?rx"P"P"PQQRRC#&t}#7#7T]_9M9M"N!ORS!SHRhr2!!#vn'=tQR?RSSS$$RR &*++^, .* %     !F8""$$G$$$wS=P=P`d`rssssr    )r   r   r   r   )
r   r!   r"   r#   r   r$   r   r$   r   r%   )r7   r8   r   r   )	__name__
__module____qualname____doc__r   r,   r   rn   __classcell__)r   s   @r   r
   r
      s         4" " " " " "   <F F F't 't 't 't 't 't 't 'tr    r
   )
__future__r   typingr   numpyrU   ultralytics.solutions.solutionsr   r   r   ultralytics.utils.plottingr   r
   r   r    r   <module>ry      s    # " " " " "           \ \ \ \ \ \ \ \ \ \ - - - - - -xt xt xt xt xtL xt xt xt xt xtr    