Ë
    Fêñi‰  ã                  óZ   — 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y)é    )Úannotations)ÚAnyN)ÚBaseSolutionÚSolutionAnnotatorÚSolutionResults)Úcolorsc                  óN   ‡ — 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}")
    c                ó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)ÚselfÚkwargsÚ	__class__s     €úf/var/www/pod-logistic/pod-ai/venv/lib/python3.12/site-packages/ultralytics/solutions/region_counter.pyr   zRegionCounter.__init__(   sJ   ø€ ä‰ÑÑ"˜6Ò"à$ØØØ+Ø#ñ 
ˆÔð  ˆÔØ "ˆÔØ×ÑÕ!ó    c                óº   — | j                   j                  «       }|j                  || j                  |«      ||dœ«       | j                  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   Úpolygon_pointsr   r   Úregions         r   Ú
add_regionzRegionCounter.add_region6   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)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Ô,Ø&¨¯©Ð4ˆDŒKÜ'¨¯©×(9Ñ(9Ó(;Ó<ò 	F‰NˆA‰{��cØ—_‘_ T¨3´°q¸$³ÀÓQˆFØ)-¯©°6¸)Ñ3DÓ)EˆFÐ%Ò&ñ	Fr   c           
     óØ  — | 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 �]  }|d   }	t        t!        t"        t%        j&                  |	j(                  j*                  t$        j,                  ¬«      «      «      }
t/        |	j0                  j2                  «      t/        |	j0                  j4                  «      fgdz  \  \  }}\  }}|j7                  |
|d   | j                  dz  «       |j9                  ||||gt;        |d	   «      |d   |d   | j                  dz  d¬«       d|d	<   �Œ |j=                  «       }| j?                  |«       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)r3   r4   Ú	txt_colorÚmarginÚshape)Úplot_imÚtotal_tracksr   )"Úextract_tracksr   r2   Ú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_labelÚstrÚresultÚdisplay_outputr   Úlen)r   Úim0Ú	annotatorÚboxÚclsÚtrack_idÚconfÚcenterr%   Úpolyr0   Úx1Úy1Úx2Úy2r>   s                   r   ÚprocesszRegionCounter.process^   sK  € ð 	×Ñ˜CÔ Ü% c°d·o±oÔFˆ	ä(+¨D¯J©J¸¿	¹	À4Ç>Á>ÐSW×S]ÑS]Ó(^ò 	JÑ$ˆC��h Ø×Ñ ¨4×+@Ñ+@ÀÀdÈHÓ+UÔ]cÐdlÐnrÓ]sÐÔtØ—Z‘Z # a¡&¨3¨q©6¡/°QÑ!6¸¸Q¹À#ÀaÁ&¹ÈAÑ8MÐ NÓOˆFØ×/Ñ/ò J�ØÐ,Ñ-×6Ñ6°vÕ>Ø˜8Ó$¨Ñ)Ó$Ø9?ÀÑ9I�D×&Ñ& v¨f¡~Ò6ñJð	Jð ×+Ñ+ó 	!ˆFØ˜)Ñ$ˆDÜ”sœ5¤"§(¡(¨4¯=©=×+?Ñ+?ÄrÇxÁxÔ"PÓQÓRˆCÜ#& t§}¡}§¡Ó#7¼¸T¿]¹]¿_¹_Ó9MÐ"NÐ!OÐRSÑ!SÑ‰HˆR�‘h�r˜2Ø×!Ñ! # v¨nÑ'=¸t¿¹ÐQRÑ?RÔSØ×$Ñ$Ø�R˜˜RÐ Ü˜& Ñ*Ó+Ø˜^Ñ,Ø  Ñ.Ø—‘¨Ñ*Øð %ô ð  !ˆF�8Óð	!ð ×"Ñ"Ó$ˆØ×Ñ˜GÔ$ä w¼SÀÇÁÓ=PÐ`d×`rÑ`rÔsÐsr   )r   r   ÚreturnÚNone)
r   rX   r$   zlist[tuple]r   útuple[int, int, int]r   rk   ri   zdict[str, Any])r\   z
np.ndarrayri   r   )	Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r&   r   rh   Ú__classcell__)r   s   @r   r
   r
      sN   ø„ ñõ4"ðàðð $ðð +ð	ð
 )ðð 
óò<F÷'tr   r
   )Ú
__future__r   Útypingr   ÚnumpyrM   Úultralytics.solutions.solutionsr   r   r   Úultralytics.utils.plottingr   r
   r   r   r   ú<module>rv      s)   ðõ #å ã ç \Ñ \Ý -ôxt�Lõ xtr   