
    |h                     V    d dl mZmZ d dlZd dlZd dlmZ d dlm	Z	m
Z
  G d de      Zy)    )AnyListN)ObjectCounter)SolutionAnnotatorSolutionResultsc                   f     e Zd ZdZdeddf fdZdee   ddfdZde	j                  defd	Z x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)
    kwargsreturnNc                     t        |   di | d| _        | j                  | j	                          | j
                  d   | _        d| _        y)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CFGr   heatmap)selfr
   	__class__s     \/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/solutions/heatmap.pyr   zHeatmap.__init__$   sL     	"6" ;;"""$ ,    boxc                 d   t        t        |      \  }}}}t        ||z
  ||z
        dz  dz  }t        j                  t        j
                  ||      t        j
                  ||            \  }}|||z   dz  z
  dz  |||z   dz  z
  dz  z   }	|	|k  }
| j                  ||||f   |
xx   dz  cc<   y)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   r   x0y0x1y1radius_squaredxvyvdist_squaredwithin_radiuss              r   heatmap_effectzHeatmap.heatmap_effect5   s     S#BBb2grBw/14: RYYr2.		"b0ABB rBw1n-!3rb2g!^7LQR6RR %6 	RUBrE\"=1Q61r   im0c           	         | j                   s4t        j                  |t        j                        dz  | _        d| _         | j                  |       t        || j                        | _        t        | j                  | j                  | j                        D ]  \  }}}| j                  |       | j                  %| j                  j                  | j                  d| j                  dz         | j!                  ||       d}t#        | j$                  |         d	kD  r| j$                  |   d
   }| j'                  | j$                  |   d   |||        | j                  j)                         }| j                  | j+                  |       | j,                  j.                  rt1        j2                  | j                  dddt0        j4                        j7                  t        j8                        }t1        j:                  || j<                        }t1        j>                  |d|dd      }| jA                  |       tC        || jD                  | jF                  tI        | jJ                        t#        | j                              S )a  
        Generate heatmap for each frame using Ultralytics tracking.

        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	thickness   r      g      ?)plot_imin_count	out_countclasswise_counttotal_tracks)&r   r    
zeros_likefloat32r   extract_tracksr   r0   	annotatorzipboxes	track_idsclssr,   r   draw_regionstore_tracking_historylentrack_historycount_objectsresultdisplay_counts
track_datais_trackcv2	normalizeNORM_MINMAXastypeuint8applyColorMapr   addWeighteddisplay_outputr   r;   r<   dictr=   )	r   r-   r   track_idclsprev_positionr:   normalized_heatmapcolored_heatmaps	            r   processzHeatmap.processK   s	    ==BJJ?$FDL#DC *34??K #&djj$..$))"L 	cC3${{&**4;;m_c_n_nqr_r*s++Hc: $t))(34q8$($6$6x$@$DM""4#5#5h#?#CX}^ab	c ..'');;"( ??##!$t||T1c3??![!b!bceckck!l!//0BDMMROoogsOS!LGG$ ]]nn !5!56T^^,
 	
r   )__name__
__module____qualname____doc__r   r   r   floatr,   r    ndarrayr   r^   __classcell__)r   s   @r   r	   r	      sI    .  "7$u+ 7$ 7,6
2:: 6
/ 6
r   r	   )typingr   r   rP   numpyr    $ultralytics.solutions.object_counterr   ultralytics.solutions.solutionsr   r   r	   r   r   r   <module>rj      s$     
  > Nu
m u
r   