Guides/Advanced/10 React to events in real time

React to events in real time

1from lynx import LYNX
2
3model = LYNX("lynx-basic", track=True)
4
5def on_apple(result, det_idx):
6 print(f"apple at {result.boxes.xyxy[det_idx]}")
7
8model.on_detect("apple", on_apple)
9model.on_detect(["apple", "banana"], on_apple) # multiple classes

Callbacks let the model fire your code when something happens, instead of you writing the "if any detection matches X then…" branch yourself for every frame. Same logic, less code, fewer bugs from off-by-one frame indexing.

Pair with track=True. on_detect("apple", ...) without tracking fires per-detection-per-frame — a single apple in view for 60 seconds at 30fps fires 1800 callbacks. Almost always you want "fire once per unique apple", which requires tracking IDs. With track=True, downstream callbacks like on_enter_zone() and on_line_cross() also have stable identities to fire on.

Available hooks:

  • on_detect(classes, callback) — class(es) present in a frame
  • on_enter_zone(zone, callback) / on_exit_zone(zone, callback) — track crosses a polygon boundary
  • on_line_cross(line, callback) — track crosses a line (directional, useful for counting "entered vs exited")
  • on_behavior(labels, callback) — temporal behavior classifier fires (requires behavior=True)

Don't do heavy work inside a callback. Callbacks fire on the inference loop's thread; expensive work (DB writes, HTTP requests, image saving) blocks the next frame. Push to a queue, dispatch from a worker thread.

Next
Measure real-world distance
Bounding boxes give you shape; depth gives you "how far away is that thing".