§
    l¬¸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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Úprepared_polygonÚcountsÚregion_colorÚ
text_color© )ÚsuperÚ__init__Úregion_templateÚregion_countsÚcounting_regionsÚinitialize_regions)Úselfr   Ú	__class__s     €út/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/ultralytics/solutions/region_counter.pyr   zRegionCounter.__init__(   sk   ø€ à�‰ŒÔÐ"Ð"˜6Ð"Ð"Ð"à$ØØ $ØØ+Ø#ð 
ð  
ˆÔð  ˆÔØ "ˆÔØ×ÒÑ!Ô!Ð!Ð!Ð!ó    r   ÚstrÚpolygon_pointsúlist[tuple]r   útuple[int, int, int]r   údict[str, Any]c                ó^  — t          |¦  «        dk     r#t          dt          |¦  «        › d|› d�¦  «        ‚|                      |¦  «        }| 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.
        é   zQRegionCounter requires regions with at least 3 points to form a polygon, but got z for 'z'.)r   r   r   r   r   )	ÚlenÚ
ValueErrorÚPolygonr   ÚcopyÚupdateÚprepr   Úappend)r   r   r#   r   r   r   Úregions          r    Ú
add_regionzRegionCounter.add_region7   sÕ   € õ$ ˆ~ÑÔ Ò"Ð"Ýð?Ý˜~Ñ.Ô.ð?ð ?Ø6:ð?ð ?ð ?ñô ð ð —,’,˜~Ñ.Ô.ˆØÔ%×*Ò*Ñ,Ô,ˆØ�ŠàØ"Ø$(§I¢I¨gÑ$6Ô$6Ø ,Ø(ðð ñ	
ô 	
ð 	
ð 	Ô×$Ò$ VÑ,Ô,Ð,Øˆr!   c           	     ó6  — | j         €|                      ¦   «          t          | j         t          ¦  «        sd| j         i| _         t	          | j                              ¦   «         ¦  «        D ].\  }\  }}|                      ||t          |d¦  «        d¦  «         Œ/dS )z0Initialize regions from `self.region` only once.Nz	Region#01Tr   )r0   Úinitialize_regionÚ
isinstanceÚdictÚ	enumerateÚitemsr1   r   )r   Úir   Úptss       r    r   z RegionCounter.initialize_regions\   sœ   € àŒ;ÐØ×"Ò"Ñ$Ô$Ð$Ý˜$œ+¥tÑ,Ô,ð 	5Ø&¨¬Ð4ˆDŒKÝ'¨¬×(9Ò(9Ñ(;Ô(;Ñ<Ô<ð 	Ið 	I‰NˆA‰{��cØ�OŠO˜D #¥v¨a°¡¤¸ÑHÔHÐHÐHð	Ið 	Ir!   Úim0ú
np.ndarrayr   c           
     ó$  — |                       |¦  «         t          || j        ¬¦  «        }d„ | j        D ¦   «         | _        t          | j        | j        | j        | j	        ¦  «        D ]Ê\  }}}}| 
                    ||                      |||¦  «        t          |d¦  «        ¬¦  «         |                      |¦  «        \  }}}	}
|                      ||	z   dz  ||
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        ¬¦  «        ¦  «        ¦  «        }t1          |j        j        ¦  «        t1          |j        j        ¦  «        fgdz  \  \  }	}
\  }}|                     ||d         | j        dz  ¦  «         |                     |	|
||gt=          |d         ¦  «        |d         |d         | j        dz  d¬¦  «         d|d<   �Œ|                     ¦   «         }|                       |¦  «         tC          |tE          | 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_widthc                ó    — i | ]}|d          d“ŒS )r   r   r   )Ú.0r0   s     r    ú
<dictcomp>z)RegionCounter.process.<locals>.<dictcomp>q   s   € ÐTÐTÐT°F˜f Vœn¨aÐTÐTÐTr!   T)ÚlabelÚcoloré   r   r   é   r   r   )Údtyper   r   é   Úrect)rA   rB   Ú	txt_colorÚmarginÚshaper   )Úplot_imÚtotal_tracksr   )#Úextract_tracksr   r=   r   r   ÚzipÚboxesÚclssÚ	track_idsÚconfsÚ	box_labelÚadjust_box_labelr   Úget_enclosing_boxÚPointÚcontainsÚlistÚmapÚtupleÚnpÚarrayÚexteriorÚcoordsÚint32ÚintÚcentroidÚxÚyÚdraw_regionÚadaptive_labelr"   ÚresultÚdisplay_outputr   r)   )r   r:   Ú	annotatorÚboxÚclsÚtrack_idÚconfÚx0Úy0Úx1Úy1Úcenterr0   Úpolyr9   Úx2Úy2rK   s                     r    ÚprocesszRegionCounter.processe   s±  € ð 	×Ò˜CÑ Ô Ð Ý% c°d´oÐFÑFÔFˆ	ØTÐT¸dÔ>SÐTÑTÔTˆÔå(+¨D¬J¸¼	À4Ä>ÐSWÔS]Ñ(^Ô(^ð 	Jð 	JÑ$ˆC��h Ø×Ò ¨4×+@Ò+@ÀÀdÈHÑ+UÔ+UÕ]cÐdlÐnrÑ]sÔ]sÐÑtÔtÐtØ!×3Ò3°CÑ8Ô8‰NˆB��B˜Ø—Z’Z " r¡'¨Q¡°°b±¸A±Ð >Ñ?Ô?ˆFØÔ/ð Jð J�ØÐ,Ô-×6Ò6°vÑ>Ô>ð JØ˜8Ð$Ð$Ô$¨Ñ)Ð$Ð$Ñ$Ø9?ÀÔ9I�DÔ& v¨f¤~Ñ6øðJð Ô+ð 	!ñ 	!ˆFØ˜)Ô$ˆDÝ•s�5¥"¤(¨4¬=Ô+?ÅrÄxÐ"PÑ"PÔ"PÑQÔQÑRÔRˆCÝ#& t¤}¤Ñ#7Ô#7½¸T¼]¼_Ñ9MÔ9MÐ"NÐ!OÐRSÑ!SÑ‰HˆR�‘h�r˜2Ø×!Ò! # v¨nÔ'=¸t¼ÐQRÑ?RÑSÔSÐSØ×$Ò$Ø�R˜˜RÐ Ý˜& Ô*Ñ+Ô+Ø˜^Ô,Ø  Ô.Ø”¨Ñ*Øð %ñ ô ð ð  !ˆF�8ÑÑØ×"Ò"Ñ$Ô$ˆØ×Ò˜GÑ$Ô$Ð$å w½SÀÄÑ=PÔ=PÐ`dÔ`rÐsÑsÔsÐsr!   )r   r   r   r   )
r   r"   r#   r$   r   r%   r   r%   r   r&   )r:   r;   r   r   )	Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r1   r   ru   Ú__classcell__)r   s   @r    r
   r
      sŠ   ø€ € € € € ðð ð4"ð "ð "ð "ð "ð "ð#ð #ð #ð #ðJIð Ið Ið)tð )tð )tð )tð )tð )tð )tð )tr!   r
   )Ú
__future__r   Útypingr   Únumpyr[   Úultralytics.solutions.solutionsr   r   r   Úultralytics.utils.plottingr   r
   r   r!   r    ú<module>r€      s¯   ðð #Ð "Ð "Ð "Ð "Ð "à Ð Ð Ð Ð Ð à Ð Ð Ð à \Ð \Ð \Ð \Ð \Ð \Ð \Ð \Ð \Ð \Ø -Ð -Ð -Ð -Ð -Ð -ðAtð Atð Atð Atð At�Lñ Atô Atð Atð Atð Atr!   