object_processing.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. import base64
  2. import copy
  3. import datetime
  4. import hashlib
  5. import itertools
  6. import json
  7. import logging
  8. import os
  9. import queue
  10. import threading
  11. import time
  12. from collections import Counter, defaultdict
  13. from statistics import mean, median
  14. from typing import Callable, Dict
  15. import cv2
  16. import numpy as np
  17. from frigate.config import CameraConfig, SnapshotsConfig, RecordConfig, FrigateConfig
  18. from frigate.const import CACHE_DIR, CLIPS_DIR, RECORD_DIR
  19. from frigate.edgetpu import load_labels
  20. from frigate.util import (
  21. SharedMemoryFrameManager,
  22. calculate_region,
  23. draw_box_with_label,
  24. draw_timestamp,
  25. )
  26. logger = logging.getLogger(__name__)
  27. def on_edge(box, frame_shape):
  28. if (
  29. box[0] == 0
  30. or box[1] == 0
  31. or box[2] == frame_shape[1] - 1
  32. or 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(
  41. current_thumb["box"], frame_shape
  42. ):
  43. return False
  44. # if the score is better by more than 5%
  45. if new_obj["score"] > current_thumb["score"] + 0.05:
  46. return True
  47. # if the area is 10% larger
  48. if new_obj["area"] > current_thumb["area"] * 1.1:
  49. return True
  50. return False
  51. class TrackedObject:
  52. def __init__(
  53. self, camera, colormap, camera_config: CameraConfig, frame_cache, obj_data
  54. ):
  55. self.obj_data = obj_data
  56. self.camera = camera
  57. self.colormap = colormap
  58. self.camera_config = camera_config
  59. self.frame_cache = frame_cache
  60. self.current_zones = []
  61. self.entered_zones = set()
  62. self.false_positive = True
  63. self.has_clip = False
  64. self.has_snapshot = False
  65. self.top_score = self.computed_score = 0.0
  66. self.thumbnail_data = None
  67. self.last_updated = 0
  68. self.last_published = 0
  69. self.frame = None
  70. self.previous = self.to_dict()
  71. # start the score history
  72. self.score_history = [self.obj_data["score"]]
  73. def _is_false_positive(self):
  74. # once a true positive, always a true positive
  75. if not self.false_positive:
  76. return False
  77. threshold = self.camera_config.objects.filters[self.obj_data["label"]].threshold
  78. return self.computed_score < threshold
  79. def compute_score(self):
  80. scores = self.score_history[:]
  81. # pad with zeros if you dont have at least 3 scores
  82. if len(scores) < 3:
  83. scores += [0.0] * (3 - len(scores))
  84. return median(scores)
  85. def update(self, current_frame_time, obj_data):
  86. significant_update = False
  87. zone_change = False
  88. self.obj_data.update(obj_data)
  89. # if the object is not in the current frame, add a 0.0 to the score history
  90. if self.obj_data["frame_time"] != current_frame_time:
  91. self.score_history.append(0.0)
  92. else:
  93. self.score_history.append(self.obj_data["score"])
  94. # only keep the last 10 scores
  95. if len(self.score_history) > 10:
  96. self.score_history = self.score_history[-10:]
  97. # calculate if this is a false positive
  98. self.computed_score = self.compute_score()
  99. if self.computed_score > self.top_score:
  100. self.top_score = self.computed_score
  101. self.false_positive = self._is_false_positive()
  102. if not self.false_positive:
  103. # determine if this frame is a better thumbnail
  104. if self.thumbnail_data is None or is_better_thumbnail(
  105. self.thumbnail_data, self.obj_data, self.camera_config.frame_shape
  106. ):
  107. self.thumbnail_data = {
  108. "frame_time": self.obj_data["frame_time"],
  109. "box": self.obj_data["box"],
  110. "area": self.obj_data["area"],
  111. "region": self.obj_data["region"],
  112. "score": self.obj_data["score"],
  113. }
  114. significant_update = True
  115. # check zones
  116. current_zones = []
  117. bottom_center = (self.obj_data["centroid"][0], self.obj_data["box"][3])
  118. # check each zone
  119. for name, zone in self.camera_config.zones.items():
  120. # if the zone is not for this object type, skip
  121. if len(zone.objects) > 0 and not self.obj_data["label"] in zone.objects:
  122. continue
  123. contour = zone.contour
  124. # check if the object is in the zone
  125. if cv2.pointPolygonTest(contour, bottom_center, False) >= 0:
  126. # if the object passed the filters once, dont apply again
  127. if name in self.current_zones or not zone_filtered(self, zone.filters):
  128. current_zones.append(name)
  129. self.entered_zones.add(name)
  130. # if the zones changed, signal an update
  131. if not self.false_positive and set(self.current_zones) != set(current_zones):
  132. zone_change = True
  133. self.current_zones = current_zones
  134. return (significant_update, zone_change)
  135. def to_dict(self, include_thumbnail: bool = False):
  136. snapshot_time = (
  137. self.thumbnail_data["frame_time"]
  138. if not self.thumbnail_data is None
  139. else 0.0
  140. )
  141. event = {
  142. "id": self.obj_data["id"],
  143. "camera": self.camera,
  144. "frame_time": self.obj_data["frame_time"],
  145. "snapshot_time": snapshot_time,
  146. "label": self.obj_data["label"],
  147. "top_score": self.top_score,
  148. "false_positive": self.false_positive,
  149. "start_time": self.obj_data["start_time"],
  150. "end_time": self.obj_data.get("end_time", None),
  151. "score": self.obj_data["score"],
  152. "box": self.obj_data["box"],
  153. "area": self.obj_data["area"],
  154. "region": self.obj_data["region"],
  155. "motionless_count": self.obj_data["motionless_count"],
  156. "current_zones": self.current_zones.copy(),
  157. "entered_zones": list(self.entered_zones).copy(),
  158. "has_clip": self.has_clip,
  159. "has_snapshot": self.has_snapshot,
  160. }
  161. if include_thumbnail:
  162. event["thumbnail"] = base64.b64encode(self.get_thumbnail()).decode("utf-8")
  163. return event
  164. def get_thumbnail(self):
  165. if (
  166. self.thumbnail_data is None
  167. or self.thumbnail_data["frame_time"] not in self.frame_cache
  168. ):
  169. ret, jpg = cv2.imencode(".jpg", np.zeros((175, 175, 3), np.uint8))
  170. jpg_bytes = self.get_jpg_bytes(
  171. timestamp=False, bounding_box=False, crop=True, height=175
  172. )
  173. if jpg_bytes:
  174. return jpg_bytes
  175. else:
  176. ret, jpg = cv2.imencode(".jpg", np.zeros((175, 175, 3), np.uint8))
  177. return jpg.tobytes()
  178. def get_clean_png(self):
  179. if self.thumbnail_data is None:
  180. return None
  181. try:
  182. best_frame = cv2.cvtColor(
  183. self.frame_cache[self.thumbnail_data["frame_time"]],
  184. cv2.COLOR_YUV2BGR_I420,
  185. )
  186. except KeyError:
  187. logger.warning(
  188. f"Unable to create clean png because frame {self.thumbnail_data['frame_time']} is not in the cache"
  189. )
  190. return None
  191. ret, png = cv2.imencode(".png", best_frame)
  192. if ret:
  193. return png.tobytes()
  194. else:
  195. return None
  196. def get_jpg_bytes(
  197. self, timestamp=False, bounding_box=False, crop=False, height=None, quality=70
  198. ):
  199. if self.thumbnail_data is None:
  200. return None
  201. try:
  202. best_frame = cv2.cvtColor(
  203. self.frame_cache[self.thumbnail_data["frame_time"]],
  204. cv2.COLOR_YUV2BGR_I420,
  205. )
  206. except KeyError:
  207. logger.warning(
  208. f"Unable to create jpg because frame {self.thumbnail_data['frame_time']} is not in the cache"
  209. )
  210. return None
  211. if bounding_box:
  212. thickness = 2
  213. color = self.colormap[self.obj_data["label"]]
  214. # draw the bounding boxes on the frame
  215. box = self.thumbnail_data["box"]
  216. draw_box_with_label(
  217. best_frame,
  218. box[0],
  219. box[1],
  220. box[2],
  221. box[3],
  222. self.obj_data["label"],
  223. f"{int(self.thumbnail_data['score']*100)}% {int(self.thumbnail_data['area'])}",
  224. thickness=thickness,
  225. color=color,
  226. )
  227. if crop:
  228. box = self.thumbnail_data["box"]
  229. region = calculate_region(
  230. best_frame.shape, box[0], box[1], box[2], box[3], 1.1
  231. )
  232. best_frame = best_frame[region[1] : region[3], region[0] : region[2]]
  233. if height:
  234. width = int(height * best_frame.shape[1] / best_frame.shape[0])
  235. best_frame = cv2.resize(
  236. best_frame, dsize=(width, height), interpolation=cv2.INTER_AREA
  237. )
  238. if timestamp:
  239. color = self.camera_config.timestamp_style.color
  240. draw_timestamp(
  241. best_frame,
  242. self.thumbnail_data["frame_time"],
  243. self.camera_config.timestamp_style.format,
  244. font_effect=self.camera_config.timestamp_style.effect,
  245. font_thickness=self.camera_config.timestamp_style.thickness,
  246. font_color=(color.blue, color.green, color.red),
  247. position=self.camera_config.timestamp_style.position,
  248. )
  249. ret, jpg = cv2.imencode(
  250. ".jpg", best_frame, [int(cv2.IMWRITE_JPEG_QUALITY), quality]
  251. )
  252. if ret:
  253. return jpg.tobytes()
  254. else:
  255. return None
  256. def zone_filtered(obj: TrackedObject, object_config):
  257. object_name = obj.obj_data["label"]
  258. if object_name in object_config:
  259. obj_settings = object_config[object_name]
  260. # if the min area is larger than the
  261. # detected object, don't add it to detected objects
  262. if obj_settings.min_area > obj.obj_data["area"]:
  263. return True
  264. # if the detected object is larger than the
  265. # max area, don't add it to detected objects
  266. if obj_settings.max_area < obj.obj_data["area"]:
  267. return True
  268. # if the score is lower than the threshold, skip
  269. if obj_settings.threshold > obj.computed_score:
  270. return True
  271. return False
  272. # Maintains the state of a camera
  273. class CameraState:
  274. def __init__(
  275. self, name, config: FrigateConfig, frame_manager: SharedMemoryFrameManager
  276. ):
  277. self.name = name
  278. self.config = config
  279. self.camera_config = config.cameras[name]
  280. self.frame_manager = frame_manager
  281. self.best_objects: Dict[str, TrackedObject] = {}
  282. self.object_counts = defaultdict(int)
  283. self.tracked_objects: Dict[str, TrackedObject] = {}
  284. self.frame_cache = {}
  285. self.zone_objects = defaultdict(list)
  286. self._current_frame = np.zeros(self.camera_config.frame_shape_yuv, np.uint8)
  287. self.current_frame_lock = threading.Lock()
  288. self.current_frame_time = 0.0
  289. self.motion_boxes = []
  290. self.regions = []
  291. self.previous_frame_id = None
  292. self.callbacks = defaultdict(list)
  293. def get_current_frame(self, draw_options={}):
  294. with self.current_frame_lock:
  295. frame_copy = np.copy(self._current_frame)
  296. frame_time = self.current_frame_time
  297. tracked_objects = {k: v.to_dict() for k, v in self.tracked_objects.items()}
  298. motion_boxes = self.motion_boxes.copy()
  299. regions = self.regions.copy()
  300. frame_copy = cv2.cvtColor(frame_copy, cv2.COLOR_YUV2BGR_I420)
  301. # draw on the frame
  302. if draw_options.get("bounding_boxes"):
  303. # draw the bounding boxes on the frame
  304. for obj in tracked_objects.values():
  305. if obj["frame_time"] == frame_time:
  306. thickness = 2
  307. color = self.config.model.colormap[obj["label"]]
  308. else:
  309. thickness = 1
  310. color = (255, 0, 0)
  311. # draw the bounding boxes on the frame
  312. box = obj["box"]
  313. draw_box_with_label(
  314. frame_copy,
  315. box[0],
  316. box[1],
  317. box[2],
  318. box[3],
  319. obj["label"],
  320. f"{obj['score']:.0%} {int(obj['area'])}",
  321. thickness=thickness,
  322. color=color,
  323. )
  324. if draw_options.get("regions"):
  325. for region in regions:
  326. cv2.rectangle(
  327. frame_copy,
  328. (region[0], region[1]),
  329. (region[2], region[3]),
  330. (0, 255, 0),
  331. 2,
  332. )
  333. if draw_options.get("zones"):
  334. for name, zone in self.camera_config.zones.items():
  335. thickness = (
  336. 8
  337. if any(
  338. name in obj["current_zones"] for obj in tracked_objects.values()
  339. )
  340. else 2
  341. )
  342. cv2.drawContours(frame_copy, [zone.contour], -1, zone.color, thickness)
  343. if draw_options.get("mask"):
  344. mask_overlay = np.where(self.camera_config.motion.mask == [0])
  345. frame_copy[mask_overlay] = [0, 0, 0]
  346. if draw_options.get("motion_boxes"):
  347. for m_box in motion_boxes:
  348. cv2.rectangle(
  349. frame_copy,
  350. (m_box[0], m_box[1]),
  351. (m_box[2], m_box[3]),
  352. (0, 0, 255),
  353. 2,
  354. )
  355. if draw_options.get("timestamp"):
  356. color = self.camera_config.timestamp_style.color
  357. draw_timestamp(
  358. frame_copy,
  359. frame_time,
  360. self.camera_config.timestamp_style.format,
  361. font_effect=self.camera_config.timestamp_style.effect,
  362. font_thickness=self.camera_config.timestamp_style.thickness,
  363. font_color=(color.blue, color.green, color.red),
  364. position=self.camera_config.timestamp_style.position,
  365. )
  366. return frame_copy
  367. def finished(self, obj_id):
  368. del self.tracked_objects[obj_id]
  369. def on(self, event_type: str, callback: Callable[[Dict], None]):
  370. self.callbacks[event_type].append(callback)
  371. def update(self, frame_time, current_detections, motion_boxes, regions):
  372. # get the new frame
  373. frame_id = f"{self.name}{frame_time}"
  374. current_frame = self.frame_manager.get(
  375. frame_id, self.camera_config.frame_shape_yuv
  376. )
  377. tracked_objects = self.tracked_objects.copy()
  378. current_ids = set(current_detections.keys())
  379. previous_ids = set(tracked_objects.keys())
  380. removed_ids = previous_ids.difference(current_ids)
  381. new_ids = current_ids.difference(previous_ids)
  382. updated_ids = current_ids.intersection(previous_ids)
  383. for id in new_ids:
  384. new_obj = tracked_objects[id] = TrackedObject(
  385. self.name,
  386. self.config.model.colormap,
  387. self.camera_config,
  388. self.frame_cache,
  389. current_detections[id],
  390. )
  391. # call event handlers
  392. for c in self.callbacks["start"]:
  393. c(self.name, new_obj, frame_time)
  394. for id in updated_ids:
  395. updated_obj = tracked_objects[id]
  396. significant_update, zone_change = updated_obj.update(
  397. frame_time, current_detections[id]
  398. )
  399. if significant_update:
  400. # ensure this frame is stored in the cache
  401. if (
  402. updated_obj.thumbnail_data["frame_time"] == frame_time
  403. and frame_time not in self.frame_cache
  404. ):
  405. self.frame_cache[frame_time] = np.copy(current_frame)
  406. updated_obj.last_updated = frame_time
  407. # if it has been more than 5 seconds since the last publish
  408. # and the last update is greater than the last publish or
  409. # the object has changed zones
  410. if (
  411. frame_time - updated_obj.last_published > 5
  412. and updated_obj.last_updated > updated_obj.last_published
  413. ) or zone_change:
  414. # call event handlers
  415. for c in self.callbacks["update"]:
  416. c(self.name, updated_obj, frame_time)
  417. updated_obj.last_published = frame_time
  418. for id in removed_ids:
  419. # publish events to mqtt
  420. removed_obj = tracked_objects[id]
  421. if not "end_time" in removed_obj.obj_data:
  422. removed_obj.obj_data["end_time"] = frame_time
  423. for c in self.callbacks["end"]:
  424. c(self.name, removed_obj, frame_time)
  425. # TODO: can i switch to looking this up and only changing when an event ends?
  426. # maintain best objects
  427. for obj in tracked_objects.values():
  428. object_type = obj.obj_data["label"]
  429. # if the object's thumbnail is not from the current frame
  430. if obj.false_positive or obj.thumbnail_data["frame_time"] != frame_time:
  431. continue
  432. if object_type in self.best_objects:
  433. current_best = self.best_objects[object_type]
  434. now = datetime.datetime.now().timestamp()
  435. # if the object is a higher score than the current best score
  436. # or the current object is older than desired, use the new object
  437. if (
  438. is_better_thumbnail(
  439. current_best.thumbnail_data,
  440. obj.thumbnail_data,
  441. self.camera_config.frame_shape,
  442. )
  443. or (now - current_best.thumbnail_data["frame_time"])
  444. > self.camera_config.best_image_timeout
  445. ):
  446. self.best_objects[object_type] = obj
  447. for c in self.callbacks["snapshot"]:
  448. c(self.name, self.best_objects[object_type], frame_time)
  449. else:
  450. self.best_objects[object_type] = obj
  451. for c in self.callbacks["snapshot"]:
  452. c(self.name, self.best_objects[object_type], frame_time)
  453. # update overall camera state for each object type
  454. obj_counter = Counter(
  455. obj.obj_data["label"]
  456. for obj in tracked_objects.values()
  457. if not obj.false_positive
  458. )
  459. # report on detected objects
  460. for obj_name, count in obj_counter.items():
  461. if count != self.object_counts[obj_name]:
  462. self.object_counts[obj_name] = count
  463. for c in self.callbacks["object_status"]:
  464. c(self.name, obj_name, count)
  465. # expire any objects that are >0 and no longer detected
  466. expired_objects = [
  467. obj_name
  468. for obj_name, count in self.object_counts.items()
  469. if count > 0 and obj_name not in obj_counter
  470. ]
  471. for obj_name in expired_objects:
  472. self.object_counts[obj_name] = 0
  473. for c in self.callbacks["object_status"]:
  474. c(self.name, obj_name, 0)
  475. for c in self.callbacks["snapshot"]:
  476. c(self.name, self.best_objects[obj_name], frame_time)
  477. # cleanup thumbnail frame cache
  478. current_thumb_frames = {
  479. obj.thumbnail_data["frame_time"]
  480. for obj in tracked_objects.values()
  481. if not obj.false_positive
  482. }
  483. current_best_frames = {
  484. obj.thumbnail_data["frame_time"] for obj in self.best_objects.values()
  485. }
  486. thumb_frames_to_delete = [
  487. t
  488. for t in self.frame_cache.keys()
  489. if t not in current_thumb_frames and t not in current_best_frames
  490. ]
  491. for t in thumb_frames_to_delete:
  492. del self.frame_cache[t]
  493. with self.current_frame_lock:
  494. self.tracked_objects = tracked_objects
  495. self.current_frame_time = frame_time
  496. self.motion_boxes = motion_boxes
  497. self.regions = regions
  498. self._current_frame = current_frame
  499. if self.previous_frame_id is not None:
  500. self.frame_manager.close(self.previous_frame_id)
  501. self.previous_frame_id = frame_id
  502. class TrackedObjectProcessor(threading.Thread):
  503. def __init__(
  504. self,
  505. config: FrigateConfig,
  506. client,
  507. topic_prefix,
  508. tracked_objects_queue,
  509. event_queue,
  510. event_processed_queue,
  511. video_output_queue,
  512. recordings_info_queue,
  513. stop_event,
  514. ):
  515. threading.Thread.__init__(self)
  516. self.name = "detected_frames_processor"
  517. self.config = config
  518. self.client = client
  519. self.topic_prefix = topic_prefix
  520. self.tracked_objects_queue = tracked_objects_queue
  521. self.event_queue = event_queue
  522. self.event_processed_queue = event_processed_queue
  523. self.video_output_queue = video_output_queue
  524. self.recordings_info_queue = recordings_info_queue
  525. self.stop_event = stop_event
  526. self.camera_states: Dict[str, CameraState] = {}
  527. self.frame_manager = SharedMemoryFrameManager()
  528. def start(camera, obj: TrackedObject, current_frame_time):
  529. self.event_queue.put(("start", camera, obj.to_dict()))
  530. def update(camera, obj: TrackedObject, current_frame_time):
  531. obj.has_snapshot = self.should_save_snapshot(camera, obj)
  532. obj.has_clip = self.should_retain_recording(camera, obj)
  533. after = obj.to_dict()
  534. message = {
  535. "before": obj.previous,
  536. "after": after,
  537. "type": "new" if obj.previous["false_positive"] else "update",
  538. }
  539. self.client.publish(
  540. f"{self.topic_prefix}/events", json.dumps(message), retain=False
  541. )
  542. obj.previous = after
  543. self.event_queue.put(
  544. ("update", camera, obj.to_dict(include_thumbnail=True))
  545. )
  546. def end(camera, obj: TrackedObject, current_frame_time):
  547. # populate has_snapshot
  548. obj.has_snapshot = self.should_save_snapshot(camera, obj)
  549. obj.has_clip = self.should_retain_recording(camera, obj)
  550. # write the snapshot to disk
  551. if obj.has_snapshot:
  552. snapshot_config: SnapshotsConfig = self.config.cameras[camera].snapshots
  553. jpg_bytes = obj.get_jpg_bytes(
  554. timestamp=snapshot_config.timestamp,
  555. bounding_box=snapshot_config.bounding_box,
  556. crop=snapshot_config.crop,
  557. height=snapshot_config.height,
  558. quality=snapshot_config.quality,
  559. )
  560. if jpg_bytes is None:
  561. logger.warning(f"Unable to save snapshot for {obj.obj_data['id']}.")
  562. else:
  563. with open(
  564. os.path.join(CLIPS_DIR, f"{camera}-{obj.obj_data['id']}.jpg"),
  565. "wb",
  566. ) as j:
  567. j.write(jpg_bytes)
  568. # write clean snapshot if enabled
  569. if snapshot_config.clean_copy:
  570. png_bytes = obj.get_clean_png()
  571. if png_bytes is None:
  572. logger.warning(
  573. f"Unable to save clean snapshot for {obj.obj_data['id']}."
  574. )
  575. else:
  576. with open(
  577. os.path.join(
  578. CLIPS_DIR,
  579. f"{camera}-{obj.obj_data['id']}-clean.png",
  580. ),
  581. "wb",
  582. ) as p:
  583. p.write(png_bytes)
  584. if not obj.false_positive:
  585. message = {
  586. "before": obj.previous,
  587. "after": obj.to_dict(),
  588. "type": "end",
  589. }
  590. self.client.publish(
  591. f"{self.topic_prefix}/events", json.dumps(message), retain=False
  592. )
  593. self.event_queue.put(("end", camera, obj.to_dict(include_thumbnail=True)))
  594. def snapshot(camera, obj: TrackedObject, current_frame_time):
  595. mqtt_config = self.config.cameras[camera].mqtt
  596. if mqtt_config.enabled and self.should_mqtt_snapshot(camera, obj):
  597. jpg_bytes = obj.get_jpg_bytes(
  598. timestamp=mqtt_config.timestamp,
  599. bounding_box=mqtt_config.bounding_box,
  600. crop=mqtt_config.crop,
  601. height=mqtt_config.height,
  602. quality=mqtt_config.quality,
  603. )
  604. if jpg_bytes is None:
  605. logger.warning(
  606. f"Unable to send mqtt snapshot for {obj.obj_data['id']}."
  607. )
  608. else:
  609. self.client.publish(
  610. f"{self.topic_prefix}/{camera}/{obj.obj_data['label']}/snapshot",
  611. jpg_bytes,
  612. retain=True,
  613. )
  614. def object_status(camera, object_name, status):
  615. self.client.publish(
  616. f"{self.topic_prefix}/{camera}/{object_name}", status, retain=False
  617. )
  618. for camera in self.config.cameras.keys():
  619. camera_state = CameraState(camera, self.config, self.frame_manager)
  620. camera_state.on("start", start)
  621. camera_state.on("update", update)
  622. camera_state.on("end", end)
  623. camera_state.on("snapshot", snapshot)
  624. camera_state.on("object_status", object_status)
  625. self.camera_states[camera] = camera_state
  626. # {
  627. # 'zone_name': {
  628. # 'person': {
  629. # 'camera_1': 2,
  630. # 'camera_2': 1
  631. # }
  632. # }
  633. # }
  634. self.zone_data = defaultdict(lambda: defaultdict(dict))
  635. def should_save_snapshot(self, camera, obj: TrackedObject):
  636. if obj.false_positive:
  637. return False
  638. snapshot_config: SnapshotsConfig = self.config.cameras[camera].snapshots
  639. if not snapshot_config.enabled:
  640. return False
  641. # if there are required zones and there is no overlap
  642. required_zones = snapshot_config.required_zones
  643. if len(required_zones) > 0 and not obj.entered_zones & set(required_zones):
  644. logger.debug(
  645. f"Not creating snapshot for {obj.obj_data['id']} because it did not enter required zones"
  646. )
  647. return False
  648. return True
  649. def should_retain_recording(self, camera, obj: TrackedObject):
  650. if obj.false_positive:
  651. return False
  652. record_config: RecordConfig = self.config.cameras[camera].record
  653. # Recording is disabled
  654. if not record_config.enabled:
  655. return False
  656. # If there are required zones and there is no overlap
  657. required_zones = record_config.events.required_zones
  658. if len(required_zones) > 0 and not set(obj.entered_zones) & set(required_zones):
  659. logger.debug(
  660. f"Not creating clip for {obj.obj_data['id']} because it did not enter required zones"
  661. )
  662. return False
  663. # If the required objects are not present
  664. if (
  665. record_config.events.objects is not None
  666. and obj.obj_data["label"] not in record_config.events.objects
  667. ):
  668. logger.debug(
  669. f"Not creating clip for {obj.obj_data['id']} because it did not contain required objects"
  670. )
  671. return False
  672. return True
  673. def should_mqtt_snapshot(self, camera, obj: TrackedObject):
  674. # if there are required zones and there is no overlap
  675. required_zones = self.config.cameras[camera].mqtt.required_zones
  676. if len(required_zones) > 0 and not obj.entered_zones & set(required_zones):
  677. logger.debug(
  678. f"Not sending mqtt for {obj.obj_data['id']} because it did not enter required zones"
  679. )
  680. return False
  681. return True
  682. def get_best(self, camera, label):
  683. # TODO: need a lock here
  684. camera_state = self.camera_states[camera]
  685. if label in camera_state.best_objects:
  686. best_obj = camera_state.best_objects[label]
  687. best = best_obj.thumbnail_data.copy()
  688. best["frame"] = camera_state.frame_cache.get(
  689. best_obj.thumbnail_data["frame_time"]
  690. )
  691. return best
  692. else:
  693. return {}
  694. def get_current_frame(self, camera, draw_options={}):
  695. return self.camera_states[camera].get_current_frame(draw_options)
  696. def run(self):
  697. while not self.stop_event.is_set():
  698. try:
  699. (
  700. camera,
  701. frame_time,
  702. current_tracked_objects,
  703. motion_boxes,
  704. regions,
  705. ) = self.tracked_objects_queue.get(True, 10)
  706. except queue.Empty:
  707. continue
  708. camera_state = self.camera_states[camera]
  709. camera_state.update(
  710. frame_time, current_tracked_objects, motion_boxes, regions
  711. )
  712. tracked_objects = [
  713. o.to_dict() for o in camera_state.tracked_objects.values()
  714. ]
  715. self.video_output_queue.put(
  716. (
  717. camera,
  718. frame_time,
  719. tracked_objects,
  720. motion_boxes,
  721. regions,
  722. )
  723. )
  724. # send info on this frame to the recordings maintainer
  725. self.recordings_info_queue.put(
  726. (
  727. camera,
  728. frame_time,
  729. tracked_objects,
  730. motion_boxes,
  731. regions,
  732. )
  733. )
  734. # update zone counts for each label
  735. # for each zone in the current camera
  736. for zone in self.config.cameras[camera].zones.keys():
  737. # count labels for the camera in the zone
  738. obj_counter = Counter(
  739. obj.obj_data["label"]
  740. for obj in camera_state.tracked_objects.values()
  741. if zone in obj.current_zones and not obj.false_positive
  742. )
  743. # update counts and publish status
  744. for label in set(self.zone_data[zone].keys()) | set(obj_counter.keys()):
  745. # if we have previously published a count for this zone/label
  746. zone_label = self.zone_data[zone][label]
  747. if camera in zone_label:
  748. current_count = sum(zone_label.values())
  749. zone_label[camera] = (
  750. obj_counter[label] if label in obj_counter else 0
  751. )
  752. new_count = sum(zone_label.values())
  753. if new_count != current_count:
  754. self.client.publish(
  755. f"{self.topic_prefix}/{zone}/{label}",
  756. new_count,
  757. retain=False,
  758. )
  759. # if this is a new zone/label combo for this camera
  760. else:
  761. if label in obj_counter:
  762. zone_label[camera] = obj_counter[label]
  763. self.client.publish(
  764. f"{self.topic_prefix}/{zone}/{label}",
  765. obj_counter[label],
  766. retain=False,
  767. )
  768. # cleanup event finished queue
  769. while not self.event_processed_queue.empty():
  770. event_id, camera = self.event_processed_queue.get()
  771. self.camera_states[camera].finished(event_id)
  772. logger.info(f"Exiting object processor...")