o
    Wh                     @   s@   d dl Z d dlZd dlmZ d dlmZmZ G dd deZdS )    N)ObjectCounter)SolutionAnnotatorSolutionResultsc                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )Heatmapa  
    A class to draw heatmaps in real-time video streams based on object tracks.

    This class extends the ObjectCounter class to generate and visualize heatmaps of object movements in video
    streams. It uses tracked object positions to create a cumulative heatmap effect over time.

    Attributes:
        initialized (bool): Flag indicating whether the heatmap has been initialized.
        colormap (int): OpenCV colormap used for heatmap visualization.
        heatmap (np.ndarray): Array storing the cumulative heatmap data.
        annotator (SolutionAnnotator): Object for drawing annotations on the image.

    Methods:
        heatmap_effect: Calculate and update the heatmap effect for a given bounding box.
        process: Generate and apply the heatmap effect to each frame.

    Examples:
        >>> from ultralytics.solutions import Heatmap
        >>> heatmap = Heatmap(model="yolo11n.pt", colormap=cv2.COLORMAP_JET)
        >>> frame = cv2.imread("frame.jpg")
        >>> processed_frame = heatmap.process(frame)
    c                    sT   t  jdi | d| _| jdur|   | jd du rtjn| jd | _d| _	dS )z
        Initialize the Heatmap class for real-time video stream heatmap generation based on object tracks.

        Args:
            **kwargs (Any): Keyword arguments passed to the parent ObjectCounter class.
        FNcolormap )
super__init__initializedregioninitialize_regionCFGcv2COLORMAP_PARULAr   heatmap)selfkwargs	__class__r   Q/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/solutions/heatmap.pyr	   "   s   
 
zHeatmap.__init__c                 C   s   t t|\}}}}t|| || d d }tt||t||\}}||| d  d ||| d  d  }	|	|k}
| j||||f |
  d7  < dS )z
        Efficiently calculate heatmap area and effect location for applying colormap.

        Args:
            box (List[float]): Bounding box coordinates [x0, y0, x1, y1].
           N)mapintminnpmeshgridaranger   )r   boxx0y0x1y1radius_squaredxvyvdist_squaredwithin_radiusr   r   r   heatmap_effect3   s    (&zHeatmap.heatmap_effectc           
      C   s  | j stj|tjdd | _d| _ | | t|| jd| _t	| j
| j| jD ]U\}}}| | | jdur|| jj| jd| jd d | || | | |d	 |d  d |d
 |d  d f}d}t| j| d
krt| j| d }| |||| q'| j }| jdur| | | jjdurt| jdd	dtjtj}t|| j}	t |d|	dd	}| !| t"|| j#| j$| j%t| jdS )a  
        Generate heatmap for each frame using Ultralytics.

        Args:
            im0 (np.ndarray): Input image array for processing.

        Returns:
            (SolutionResults): Contains processed image `plot_im`,
                'in_count' (int, count of objects entering the region),
                'out_count' (int, count of objects exiting the region),
                'classwise_count' (dict, per-class object count), and
                'total_tracks' (int, total number of tracked objects).
        )dtypegGz?T)
line_widthN)h   r   {   r   )reg_ptscolor	thicknessr            g      ?)plot_imin_count	out_countclasswise_counttotal_tracks)&r
   r   
zeros_likefloat32r   extract_tracksr   r)   	annotatorzipboxes	track_idsclssr'   r   draw_regionstore_tracking_historystore_classwise_countslentrack_historycount_objectsresultdisplay_counts
track_dataidr   	normalizeNORM_MINMAXastypeuint8applyColorMapr   addWeighteddisplay_outputr   r4   r5   classwise_counts)
r   im0r   track_idclscurrent_centroidprev_positionr3   normalized_heatmapcolored_heatmapr   r   r   processI   s@   



(



zHeatmap.process)__name__
__module____qualname____doc__r	   r'   rY   __classcell__r   r   r   r   r   
   s
    r   )	r   numpyr   $ultralytics.solutions.object_counterr   ultralytics.solutions.solutionsr   r   r   r   r   r   r   <module>   s
   