heatmap.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. from collections import defaultdict
  3. import cv2
  4. import numpy as np
  5. from ultralytics.utils.checks import check_imshow, check_requirements
  6. from ultralytics.utils.plotting import Annotator
  7. check_requirements("shapely>=2.0.0")
  8. from shapely.geometry import LineString, Point, Polygon
  9. class Heatmap:
  10. """A class to draw heatmaps in real-time video stream based on their tracks."""
  11. def __init__(
  12. self,
  13. classes_names,
  14. imw=0,
  15. imh=0,
  16. colormap=cv2.COLORMAP_JET,
  17. heatmap_alpha=0.5,
  18. view_img=False,
  19. view_in_counts=True,
  20. view_out_counts=True,
  21. count_reg_pts=None,
  22. count_txt_color=(0, 0, 0),
  23. count_bg_color=(255, 255, 255),
  24. count_reg_color=(255, 0, 255),
  25. region_thickness=5,
  26. line_dist_thresh=15,
  27. line_thickness=2,
  28. decay_factor=0.99,
  29. shape="circle",
  30. ):
  31. """Initializes the heatmap class with default values for Visual, Image, track, count and heatmap parameters."""
  32. # Visual information
  33. self.annotator = None
  34. self.view_img = view_img
  35. self.shape = shape
  36. self.initialized = False
  37. self.names = classes_names # Classes names
  38. # Image information
  39. self.imw = imw
  40. self.imh = imh
  41. self.im0 = None
  42. self.tf = line_thickness
  43. self.view_in_counts = view_in_counts
  44. self.view_out_counts = view_out_counts
  45. # Heatmap colormap and heatmap np array
  46. self.colormap = colormap
  47. self.heatmap = None
  48. self.heatmap_alpha = heatmap_alpha
  49. # Predict/track information
  50. self.boxes = None
  51. self.track_ids = None
  52. self.clss = None
  53. self.track_history = defaultdict(list)
  54. # Region & Line Information
  55. self.counting_region = None
  56. self.line_dist_thresh = line_dist_thresh
  57. self.region_thickness = region_thickness
  58. self.region_color = count_reg_color
  59. # Object Counting Information
  60. self.in_counts = 0
  61. self.out_counts = 0
  62. self.count_ids = []
  63. self.class_wise_count = {}
  64. self.count_txt_color = count_txt_color
  65. self.count_bg_color = count_bg_color
  66. self.cls_txtdisplay_gap = 50
  67. # Decay factor
  68. self.decay_factor = decay_factor
  69. # Check if environment supports imshow
  70. self.env_check = check_imshow(warn=True)
  71. # Region and line selection
  72. self.count_reg_pts = count_reg_pts
  73. print(self.count_reg_pts)
  74. if self.count_reg_pts is not None:
  75. if len(self.count_reg_pts) == 2:
  76. print("Line Counter Initiated.")
  77. self.counting_region = LineString(self.count_reg_pts)
  78. elif len(self.count_reg_pts) >= 3:
  79. print("Polygon Counter Initiated.")
  80. self.counting_region = Polygon(self.count_reg_pts)
  81. else:
  82. print("Invalid Region points provided, region_points must be 2 for lines or >= 3 for polygons.")
  83. print("Using Line Counter Now")
  84. self.counting_region = LineString(self.count_reg_pts)
  85. # Shape of heatmap, if not selected
  86. if self.shape not in {"circle", "rect"}:
  87. print("Unknown shape value provided, 'circle' & 'rect' supported")
  88. print("Using Circular shape now")
  89. self.shape = "circle"
  90. def extract_results(self, tracks, _intialized=False):
  91. """
  92. Extracts results from the provided data.
  93. Args:
  94. tracks (list): List of tracks obtained from the object tracking process.
  95. """
  96. self.boxes = tracks[0].boxes.xyxy.cpu()
  97. self.clss = tracks[0].boxes.cls.cpu().tolist()
  98. self.track_ids = tracks[0].boxes.id.int().cpu().tolist()
  99. def generate_heatmap(self, im0, tracks):
  100. """
  101. Generate heatmap based on tracking data.
  102. Args:
  103. im0 (nd array): Image
  104. tracks (list): List of tracks obtained from the object tracking process.
  105. """
  106. self.im0 = im0
  107. # Initialize heatmap only once
  108. if not self.initialized:
  109. self.heatmap = np.zeros((int(self.im0.shape[0]), int(self.im0.shape[1])), dtype=np.float32)
  110. self.initialized = True
  111. self.heatmap *= self.decay_factor # decay factor
  112. self.extract_results(tracks)
  113. self.annotator = Annotator(self.im0, self.tf, None)
  114. if self.track_ids is not None:
  115. # Draw counting region
  116. if self.count_reg_pts is not None:
  117. self.annotator.draw_region(
  118. reg_pts=self.count_reg_pts, color=self.region_color, thickness=self.region_thickness
  119. )
  120. for box, cls, track_id in zip(self.boxes, self.clss, self.track_ids):
  121. # Store class info
  122. if self.names[cls] not in self.class_wise_count:
  123. self.class_wise_count[self.names[cls]] = {"IN": 0, "OUT": 0}
  124. if self.shape == "circle":
  125. center = (int((box[0] + box[2]) // 2), int((box[1] + box[3]) // 2))
  126. radius = min(int(box[2]) - int(box[0]), int(box[3]) - int(box[1])) // 2
  127. y, x = np.ogrid[0 : self.heatmap.shape[0], 0 : self.heatmap.shape[1]]
  128. mask = (x - center[0]) ** 2 + (y - center[1]) ** 2 <= radius**2
  129. self.heatmap[int(box[1]) : int(box[3]), int(box[0]) : int(box[2])] += (
  130. 2 * mask[int(box[1]) : int(box[3]), int(box[0]) : int(box[2])]
  131. )
  132. else:
  133. self.heatmap[int(box[1]) : int(box[3]), int(box[0]) : int(box[2])] += 2
  134. # Store tracking hist
  135. track_line = self.track_history[track_id]
  136. track_line.append((float((box[0] + box[2]) / 2), float((box[1] + box[3]) / 2)))
  137. if len(track_line) > 30:
  138. track_line.pop(0)
  139. prev_position = self.track_history[track_id][-2] if len(self.track_history[track_id]) > 1 else None
  140. if self.count_reg_pts is not None:
  141. # Count objects in any polygon
  142. if len(self.count_reg_pts) >= 3:
  143. is_inside = self.counting_region.contains(Point(track_line[-1]))
  144. if prev_position is not None and is_inside and track_id not in self.count_ids:
  145. self.count_ids.append(track_id)
  146. if (box[0] - prev_position[0]) * (self.counting_region.centroid.x - prev_position[0]) > 0:
  147. self.in_counts += 1
  148. self.class_wise_count[self.names[cls]]["IN"] += 1
  149. else:
  150. self.out_counts += 1
  151. self.class_wise_count[self.names[cls]]["OUT"] += 1
  152. # Count objects using line
  153. elif len(self.count_reg_pts) == 2:
  154. if prev_position is not None and track_id not in self.count_ids:
  155. distance = Point(track_line[-1]).distance(self.counting_region)
  156. if distance < self.line_dist_thresh and track_id not in self.count_ids:
  157. self.count_ids.append(track_id)
  158. if (box[0] - prev_position[0]) * (
  159. self.counting_region.centroid.x - prev_position[0]
  160. ) > 0:
  161. self.in_counts += 1
  162. self.class_wise_count[self.names[cls]]["IN"] += 1
  163. else:
  164. self.out_counts += 1
  165. self.class_wise_count[self.names[cls]]["OUT"] += 1
  166. else:
  167. for box, cls in zip(self.boxes, self.clss):
  168. if self.shape == "circle":
  169. center = (int((box[0] + box[2]) // 2), int((box[1] + box[3]) // 2))
  170. radius = min(int(box[2]) - int(box[0]), int(box[3]) - int(box[1])) // 2
  171. y, x = np.ogrid[0 : self.heatmap.shape[0], 0 : self.heatmap.shape[1]]
  172. mask = (x - center[0]) ** 2 + (y - center[1]) ** 2 <= radius**2
  173. self.heatmap[int(box[1]) : int(box[3]), int(box[0]) : int(box[2])] += (
  174. 2 * mask[int(box[1]) : int(box[3]), int(box[0]) : int(box[2])]
  175. )
  176. else:
  177. self.heatmap[int(box[1]) : int(box[3]), int(box[0]) : int(box[2])] += 2
  178. if self.count_reg_pts is not None:
  179. labels_dict = {}
  180. for key, value in self.class_wise_count.items():
  181. if value["IN"] != 0 or value["OUT"] != 0:
  182. if not self.view_in_counts and not self.view_out_counts:
  183. continue
  184. elif not self.view_in_counts:
  185. labels_dict[str.capitalize(key)] = f"OUT {value['OUT']}"
  186. elif not self.view_out_counts:
  187. labels_dict[str.capitalize(key)] = f"IN {value['IN']}"
  188. else:
  189. labels_dict[str.capitalize(key)] = f"IN {value['IN']} OUT {value['OUT']}"
  190. if labels_dict is not None:
  191. self.annotator.display_analytics(self.im0, labels_dict, self.count_txt_color, self.count_bg_color, 10)
  192. # Normalize, apply colormap to heatmap and combine with original image
  193. heatmap_normalized = cv2.normalize(self.heatmap, None, 0, 255, cv2.NORM_MINMAX)
  194. heatmap_colored = cv2.applyColorMap(heatmap_normalized.astype(np.uint8), self.colormap)
  195. self.im0 = cv2.addWeighted(self.im0, 1 - self.heatmap_alpha, heatmap_colored, self.heatmap_alpha, 0)
  196. if self.env_check and self.view_img:
  197. self.display_frames()
  198. return self.im0
  199. def display_frames(self):
  200. """Display frame."""
  201. cv2.imshow("Ultralytics Heatmap", self.im0)
  202. if cv2.waitKey(1) & 0xFF == ord("q"):
  203. return
  204. if __name__ == "__main__":
  205. classes_names = {0: "person", 1: "car"} # example class names
  206. heatmap = Heatmap(classes_names)