object_processing.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. import copy
  2. import datetime
  3. import hashlib
  4. import itertools
  5. import json
  6. import logging
  7. import os
  8. import queue
  9. import threading
  10. import time
  11. from collections import Counter, defaultdict
  12. from statistics import mean, median
  13. from typing import Callable, Dict
  14. import cv2
  15. import matplotlib.pyplot as plt
  16. import numpy as np
  17. from frigate.config import FrigateConfig, CameraConfig
  18. from frigate.edgetpu import load_labels
  19. from frigate.util import SharedMemoryFrameManager, draw_box_with_label
  20. logger = logging.getLogger(__name__)
  21. PATH_TO_LABELS = '/labelmap.txt'
  22. LABELS = load_labels(PATH_TO_LABELS)
  23. cmap = plt.cm.get_cmap('tab10', len(LABELS.keys()))
  24. COLOR_MAP = {}
  25. for key, val in LABELS.items():
  26. COLOR_MAP[val] = tuple(int(round(255 * c)) for c in cmap(key)[:3])
  27. def on_edge(box, frame_shape):
  28. if (
  29. box[0] == 0 or
  30. box[1] == 0 or
  31. box[2] == frame_shape[1]-1 or
  32. box[3] == frame_shape[0]-1
  33. ):
  34. return True
  35. def is_better_thumbnail(current_thumb, new_obj, frame_shape) -> bool:
  36. # larger is better
  37. # cutoff images are less ideal, but they should also be smaller?
  38. # better scores are obviously better too
  39. # if the new_thumb is on an edge, and the current thumb is not
  40. if on_edge(new_obj['box'], frame_shape) and not on_edge(current_thumb['box'], frame_shape):
  41. return False
  42. # if the score is better by more than 5%
  43. if new_obj['score'] > current_thumb['score']+.05:
  44. return True
  45. # if the area is 10% larger
  46. if new_obj['area'] > current_thumb['area']*1.1:
  47. return True
  48. return False
  49. class TrackedObject():
  50. def __init__(self, camera, camera_config: CameraConfig, frame_cache, obj_data):
  51. self.obj_data = obj_data
  52. self.camera = camera
  53. self.camera_config = camera_config
  54. self.frame_cache = frame_cache
  55. self.current_zones = []
  56. self.entered_zones = set()
  57. self.false_positive = True
  58. self.top_score = self.computed_score = 0.0
  59. self.thumbnail_data = None
  60. self.frame = None
  61. self._snapshot_jpg_time = 0
  62. ret, jpg = cv2.imencode('.jpg', np.zeros((300,300,3), np.uint8))
  63. self._snapshot_jpg = jpg.tobytes()
  64. # start the score history
  65. self.score_history = [self.obj_data['score']]
  66. def _is_false_positive(self):
  67. # once a true positive, always a true positive
  68. if not self.false_positive:
  69. return False
  70. threshold = self.camera_config.objects.filters[self.obj_data['label']].threshold
  71. if self.computed_score < threshold:
  72. return True
  73. return False
  74. def compute_score(self):
  75. scores = self.score_history[:]
  76. # pad with zeros if you dont have at least 3 scores
  77. if len(scores) < 3:
  78. scores += [0.0]*(3 - len(scores))
  79. return median(scores)
  80. def update(self, current_frame_time, obj_data):
  81. self.obj_data.update(obj_data)
  82. # if the object is not in the current frame, add a 0.0 to the score history
  83. if self.obj_data['frame_time'] != current_frame_time:
  84. self.score_history.append(0.0)
  85. else:
  86. self.score_history.append(self.obj_data['score'])
  87. # only keep the last 10 scores
  88. if len(self.score_history) > 10:
  89. self.score_history = self.score_history[-10:]
  90. # calculate if this is a false positive
  91. self.computed_score = self.compute_score()
  92. if self.computed_score > self.top_score:
  93. self.top_score = self.computed_score
  94. self.false_positive = self._is_false_positive()
  95. if not self.false_positive:
  96. # determine if this frame is a better thumbnail
  97. if self.thumbnail_data is None or is_better_thumbnail(self.thumbnail_data, self.obj_data, self.camera_config.frame_shape):
  98. self.thumbnail_data = {
  99. 'frame_time': self.obj_data['frame_time'],
  100. 'box': self.obj_data['box'],
  101. 'area': self.obj_data['area'],
  102. 'region': self.obj_data['region'],
  103. 'score': self.obj_data['score']
  104. }
  105. # check zones
  106. current_zones = []
  107. bottom_center = (self.obj_data['centroid'][0], self.obj_data['box'][3])
  108. # check each zone
  109. for name, zone in self.camera_config.zones.items():
  110. contour = zone.contour
  111. # check if the object is in the zone
  112. if (cv2.pointPolygonTest(contour, bottom_center, False) >= 0):
  113. # if the object passed the filters once, dont apply again
  114. if name in self.current_zones or not zone_filtered(self, zone.filters):
  115. current_zones.append(name)
  116. self.entered_zones.add(name)
  117. self.current_zones = current_zones
  118. def to_dict(self):
  119. return {
  120. 'id': self.obj_data['id'],
  121. 'camera': self.camera,
  122. 'frame_time': self.obj_data['frame_time'],
  123. 'label': self.obj_data['label'],
  124. 'top_score': self.top_score,
  125. 'false_positive': self.false_positive,
  126. 'start_time': self.obj_data['start_time'],
  127. 'end_time': self.obj_data.get('end_time', None),
  128. 'score': self.obj_data['score'],
  129. 'box': self.obj_data['box'],
  130. 'area': self.obj_data['area'],
  131. 'region': self.obj_data['region'],
  132. 'current_zones': self.current_zones.copy(),
  133. 'entered_zones': list(self.entered_zones).copy()
  134. }
  135. def get_jpg_bytes(self):
  136. if self._snapshot_jpg_time == self.thumbnail_data['frame_time']:
  137. return self._snapshot_jpg
  138. if not self.thumbnail_data['frame_time'] in self.frame_cache:
  139. logger.error(f"Unable to create thumbnail for {self.obj_data['id']}")
  140. logger.error(f"Looking for frame_time of {self.thumbnail_data['frame_time']}")
  141. logger.error(f"Thumbnail frames: {','.join([str(k) for k in self.frame_cache.keys()])}")
  142. return self._snapshot_jpg
  143. # TODO: crop first to avoid converting the entire frame?
  144. snapshot_config = self.camera_config.snapshots
  145. best_frame = cv2.cvtColor(self.frame_cache[self.thumbnail_data['frame_time']], cv2.COLOR_YUV2BGR_I420)
  146. if snapshot_config.draw_bounding_boxes:
  147. thickness = 2
  148. color = COLOR_MAP[self.obj_data['label']]
  149. box = self.thumbnail_data['box']
  150. draw_box_with_label(best_frame, box[0], box[1], box[2], box[3], self.obj_data['label'],
  151. f"{int(self.thumbnail_data['score']*100)}% {int(self.thumbnail_data['area'])}", thickness=thickness, color=color)
  152. if snapshot_config.crop_to_region:
  153. region = self.thumbnail_data['region']
  154. best_frame = best_frame[region[1]:region[3], region[0]:region[2]]
  155. if snapshot_config.height:
  156. height = snapshot_config.height
  157. width = int(height*best_frame.shape[1]/best_frame.shape[0])
  158. best_frame = cv2.resize(best_frame, dsize=(width, height), interpolation=cv2.INTER_AREA)
  159. if snapshot_config.show_timestamp:
  160. time_to_show = datetime.datetime.fromtimestamp(self.thumbnail_data['frame_time']).strftime("%m/%d/%Y %H:%M:%S")
  161. size = cv2.getTextSize(time_to_show, cv2.FONT_HERSHEY_SIMPLEX, fontScale=1, thickness=2)
  162. text_width = size[0][0]
  163. desired_size = max(200, 0.33*best_frame.shape[1])
  164. font_scale = desired_size/text_width
  165. cv2.putText(best_frame, time_to_show, (5, best_frame.shape[0]-7), cv2.FONT_HERSHEY_SIMPLEX,
  166. fontScale=font_scale, color=(255, 255, 255), thickness=2)
  167. ret, jpg = cv2.imencode('.jpg', best_frame)
  168. if ret:
  169. self._snapshot_jpg = jpg.tobytes()
  170. return self._snapshot_jpg
  171. def zone_filtered(obj: TrackedObject, object_config):
  172. object_name = obj.obj_data['label']
  173. if object_name in object_config:
  174. obj_settings = object_config[object_name]
  175. # if the min area is larger than the
  176. # detected object, don't add it to detected objects
  177. if obj_settings.min_area > obj.obj_data['area']:
  178. return True
  179. # if the detected object is larger than the
  180. # max area, don't add it to detected objects
  181. if obj_settings.max_area < obj.obj_data['area']:
  182. return True
  183. # if the score is lower than the threshold, skip
  184. if obj_settings.threshold > obj.computed_score:
  185. return True
  186. return False
  187. # Maintains the state of a camera
  188. class CameraState():
  189. def __init__(self, name, config, frame_manager):
  190. self.name = name
  191. self.config = config
  192. self.camera_config = config.cameras[name]
  193. self.frame_manager = frame_manager
  194. self.best_objects: Dict[str, TrackedObject] = {}
  195. self.object_status = defaultdict(lambda: 'OFF')
  196. self.tracked_objects: Dict[str, TrackedObject] = {}
  197. self.frame_cache = {}
  198. self.zone_objects = defaultdict(lambda: [])
  199. self._current_frame = np.zeros(self.camera_config.frame_shape_yuv, np.uint8)
  200. self.current_frame_lock = threading.Lock()
  201. self.current_frame_time = 0.0
  202. self.previous_frame_id = None
  203. self.callbacks = defaultdict(lambda: [])
  204. def get_current_frame(self, draw=False):
  205. with self.current_frame_lock:
  206. frame_copy = np.copy(self._current_frame)
  207. frame_time = self.current_frame_time
  208. tracked_objects = {k: v.to_dict() for k,v in self.tracked_objects.items()}
  209. frame_copy = cv2.cvtColor(frame_copy, cv2.COLOR_YUV2BGR_I420)
  210. # draw on the frame
  211. if draw:
  212. # draw the bounding boxes on the frame
  213. for obj in tracked_objects.values():
  214. thickness = 2
  215. color = COLOR_MAP[obj['label']]
  216. if obj['frame_time'] != frame_time:
  217. thickness = 1
  218. color = (255,0,0)
  219. # draw the bounding boxes on the frame
  220. box = obj['box']
  221. draw_box_with_label(frame_copy, box[0], box[1], box[2], box[3], obj['label'], f"{int(obj['score']*100)}% {int(obj['area'])}", thickness=thickness, color=color)
  222. # draw the regions on the frame
  223. region = obj['region']
  224. cv2.rectangle(frame_copy, (region[0], region[1]), (region[2], region[3]), (0,255,0), 1)
  225. if self.camera_config.snapshots.show_timestamp:
  226. time_to_show = datetime.datetime.fromtimestamp(frame_time).strftime("%m/%d/%Y %H:%M:%S")
  227. cv2.putText(frame_copy, time_to_show, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, fontScale=.8, color=(255, 255, 255), thickness=2)
  228. if self.camera_config.snapshots.draw_zones:
  229. for name, zone in self.camera_config.zones.items():
  230. thickness = 8 if any([name in obj['current_zones'] for obj in tracked_objects.values()]) else 2
  231. cv2.drawContours(frame_copy, [zone.contour], -1, zone.color, thickness)
  232. return frame_copy
  233. def on(self, event_type: str, callback: Callable[[Dict], None]):
  234. self.callbacks[event_type].append(callback)
  235. def update(self, frame_time, current_detections):
  236. self.current_frame_time = frame_time
  237. # get the new frame
  238. frame_id = f"{self.name}{frame_time}"
  239. current_frame = self.frame_manager.get(frame_id, self.camera_config.frame_shape_yuv)
  240. current_ids = current_detections.keys()
  241. previous_ids = self.tracked_objects.keys()
  242. removed_ids = list(set(previous_ids).difference(current_ids))
  243. new_ids = list(set(current_ids).difference(previous_ids))
  244. updated_ids = list(set(current_ids).intersection(previous_ids))
  245. for id in new_ids:
  246. new_obj = self.tracked_objects[id] = TrackedObject(self.name, self.camera_config, self.frame_cache, current_detections[id])
  247. # call event handlers
  248. for c in self.callbacks['start']:
  249. c(self.name, new_obj)
  250. for id in updated_ids:
  251. updated_obj = self.tracked_objects[id]
  252. updated_obj.update(frame_time, current_detections[id])
  253. if (not updated_obj.false_positive
  254. and updated_obj.thumbnail_data['frame_time'] == frame_time
  255. and frame_time not in self.frame_cache):
  256. self.frame_cache[frame_time] = np.copy(current_frame)
  257. # call event handlers
  258. for c in self.callbacks['update']:
  259. c(self.name, updated_obj)
  260. for id in removed_ids:
  261. # publish events to mqtt
  262. removed_obj = self.tracked_objects[id]
  263. removed_obj.obj_data['end_time'] = frame_time
  264. for c in self.callbacks['end']:
  265. c(self.name, removed_obj)
  266. del self.tracked_objects[id]
  267. # TODO: can i switch to looking this up and only changing when an event ends?
  268. # maybe make an api endpoint that pulls the thumbnail from the file system?
  269. # maintain best objects
  270. for obj in self.tracked_objects.values():
  271. object_type = obj.obj_data['label']
  272. # if the object's thumbnail is not from the current frame
  273. if obj.thumbnail_data['frame_time'] != self.current_frame_time or obj.false_positive:
  274. continue
  275. if object_type in self.best_objects:
  276. current_best = self.best_objects[object_type]
  277. now = datetime.datetime.now().timestamp()
  278. # if the object is a higher score than the current best score
  279. # or the current object is older than desired, use the new object
  280. if (is_better_thumbnail(current_best.thumbnail_data, obj.thumbnail_data, self.camera_config.frame_shape)
  281. or (now - current_best.thumbnail_data['frame_time']) > self.camera_config.best_image_timeout):
  282. self.best_objects[object_type] = obj
  283. for c in self.callbacks['snapshot']:
  284. c(self.name, self.best_objects[object_type])
  285. else:
  286. self.best_objects[object_type] = obj
  287. for c in self.callbacks['snapshot']:
  288. c(self.name, self.best_objects[object_type])
  289. # update overall camera state for each object type
  290. obj_counter = Counter()
  291. for obj in self.tracked_objects.values():
  292. if not obj.false_positive:
  293. obj_counter[obj.obj_data['label']] += 1
  294. # report on detected objects
  295. for obj_name, count in obj_counter.items():
  296. new_status = 'ON' if count > 0 else 'OFF'
  297. if new_status != self.object_status[obj_name]:
  298. self.object_status[obj_name] = new_status
  299. for c in self.callbacks['object_status']:
  300. c(self.name, obj_name, new_status)
  301. # expire any objects that are ON and no longer detected
  302. expired_objects = [obj_name for obj_name, status in self.object_status.items() if status == 'ON' and not obj_name in obj_counter]
  303. for obj_name in expired_objects:
  304. self.object_status[obj_name] = 'OFF'
  305. for c in self.callbacks['object_status']:
  306. c(self.name, obj_name, 'OFF')
  307. for c in self.callbacks['snapshot']:
  308. c(self.name, self.best_objects[obj_name])
  309. # cleanup thumbnail frame cache
  310. current_thumb_frames = set([obj.thumbnail_data['frame_time'] for obj in self.tracked_objects.values() if not obj.false_positive])
  311. current_best_frames = set([obj.thumbnail_data['frame_time'] for obj in self.best_objects.values()])
  312. thumb_frames_to_delete = [t for t in self.frame_cache.keys() if not t in current_thumb_frames and not t in current_best_frames]
  313. for t in thumb_frames_to_delete:
  314. del self.frame_cache[t]
  315. with self.current_frame_lock:
  316. self._current_frame = current_frame
  317. if not self.previous_frame_id is None:
  318. self.frame_manager.delete(self.previous_frame_id)
  319. self.previous_frame_id = frame_id
  320. class TrackedObjectProcessor(threading.Thread):
  321. def __init__(self, config: FrigateConfig, client, topic_prefix, tracked_objects_queue, event_queue, stop_event):
  322. threading.Thread.__init__(self)
  323. self.name = "detected_frames_processor"
  324. self.config = config
  325. self.client = client
  326. self.topic_prefix = topic_prefix
  327. self.tracked_objects_queue = tracked_objects_queue
  328. self.event_queue = event_queue
  329. self.stop_event = stop_event
  330. self.camera_states: Dict[str, CameraState] = {}
  331. self.frame_manager = SharedMemoryFrameManager()
  332. def start(camera, obj: TrackedObject):
  333. self.client.publish(f"{self.topic_prefix}/{camera}/events/start", json.dumps(obj.to_dict()), retain=False)
  334. self.event_queue.put(('start', camera, obj.to_dict()))
  335. def update(camera, obj: TrackedObject):
  336. pass
  337. def end(camera, obj: TrackedObject):
  338. self.client.publish(f"{self.topic_prefix}/{camera}/events/end", json.dumps(obj.to_dict()), retain=False)
  339. if self.config.cameras[camera].save_clips.enabled and not obj.false_positive:
  340. thumbnail_file_name = f"{camera}-{obj.obj_data['id']}.jpg"
  341. with open(os.path.join(self.config.save_clips.clips_dir, thumbnail_file_name), 'wb') as f:
  342. f.write(obj.get_jpg_bytes())
  343. self.event_queue.put(('end', camera, obj.to_dict()))
  344. def snapshot(camera, obj: TrackedObject):
  345. self.client.publish(f"{self.topic_prefix}/{camera}/{obj.obj_data['label']}/snapshot", obj.get_jpg_bytes(), retain=True)
  346. def object_status(camera, object_name, status):
  347. self.client.publish(f"{self.topic_prefix}/{camera}/{object_name}", status, retain=False)
  348. for camera in self.config.cameras.keys():
  349. camera_state = CameraState(camera, self.config, self.frame_manager)
  350. camera_state.on('start', start)
  351. camera_state.on('update', update)
  352. camera_state.on('end', end)
  353. camera_state.on('snapshot', snapshot)
  354. camera_state.on('object_status', object_status)
  355. self.camera_states[camera] = camera_state
  356. # {
  357. # 'zone_name': {
  358. # 'person': ['camera_1', 'camera_2']
  359. # }
  360. # }
  361. self.zone_data = defaultdict(lambda: defaultdict(lambda: set()))
  362. def get_best(self, camera, label):
  363. # TODO: need a lock here
  364. camera_state = self.camera_states[camera]
  365. if label in camera_state.best_objects:
  366. best_obj = camera_state.best_objects[label]
  367. best = best_obj.to_dict()
  368. best['frame'] = camera_state.frame_cache[best_obj.thumbnail_data['frame_time']]
  369. return best
  370. else:
  371. return {}
  372. def get_current_frame(self, camera, draw=False):
  373. return self.camera_states[camera].get_current_frame(draw)
  374. def run(self):
  375. while True:
  376. if self.stop_event.is_set():
  377. logger.info(f"Exiting object processor...")
  378. break
  379. try:
  380. camera, frame_time, current_tracked_objects = self.tracked_objects_queue.get(True, 10)
  381. except queue.Empty:
  382. continue
  383. camera_state = self.camera_states[camera]
  384. camera_state.update(frame_time, current_tracked_objects)
  385. # update zone status for each label
  386. for zone in self.config.cameras[camera].zones.keys():
  387. # get labels for current camera and all labels in current zone
  388. labels_for_camera = set([obj.obj_data['label'] for obj in camera_state.tracked_objects.values() if zone in obj.current_zones and not obj.false_positive])
  389. labels_to_check = labels_for_camera | set(self.zone_data[zone].keys())
  390. # for each label in zone
  391. for label in labels_to_check:
  392. camera_list = self.zone_data[zone][label]
  393. # remove or add the camera to the list for the current label
  394. previous_state = len(camera_list) > 0
  395. if label in labels_for_camera:
  396. camera_list.add(camera_state.name)
  397. elif camera_state.name in camera_list:
  398. camera_list.remove(camera_state.name)
  399. new_state = len(camera_list) > 0
  400. # if the value is changing, send over MQTT
  401. if previous_state == False and new_state == True:
  402. self.client.publish(f"{self.topic_prefix}/{zone}/{label}", 'ON', retain=False)
  403. elif previous_state == True and new_state == False:
  404. self.client.publish(f"{self.topic_prefix}/{zone}/{label}", 'OFF', retain=False)