object_processing.py 33 KB

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