Detect objects in a video¶
Note
A minimal example: no GPU, small models, not tuned for quality or latency. For production, work with Meetecho.
Read a video, detect the objects in it, and send a JSON event to a webhook when a class of object shows up:
Figure 1. The pipeline of this example: four nodes, one after the other.
VideoCapture reads a video file, or a webcam, and keeps at most 5 frames per second. It does not read RTSP or other network streams: for a network camera, see VideoRtp;
DetectorYolox finds the objects in each frame with YOLOX nano, one of the 80 COCO classes (people, cars, bicycles, …);
DetectionEvents turns them into one event per class, at most every 2 seconds;
NotifierHTTP posts each event to a URL.
Install¶
$ pip install juturna "juturna-nodes[video-capture,detector-yolox]"
video-capture reads the video with PyAV, detector-yolox runs the
model with ONNX Runtime.
No PyTorch and no GPU are needed.
Get a test video¶
Chinese Signal, by XZise on Wikimedia Commons, is a 9 second clip of a road crossing in 1280×720, released under CC0:
$ curl -L -o Chinese_Signal.webm \
https://upload.wikimedia.org/wikipedia/commons/3/35/Chinese_Signal.webm
The configuration¶
Save this as pipeline.json, next to the video:
{
"version": "3.0.0",
"pipeline": {
"name": "video_detection",
"id": "video_detection_01",
"folder": "./run",
"nodes": [
{ "name": "video", "type": "VideoCapture",
"configuration": { "source": "Chinese_Signal.webm", "fps": 5 } },
{ "name": "detector", "type": "DetectorYolox",
"configuration": { "model": "yolox_nano" } },
{ "name": "events", "type": "DetectionEvents",
"configuration": { "interval": 2.0 } },
{ "name": "webhook", "type": "NotifierHTTP",
"configuration": { "endpoint": "http://127.0.0.1:8080/events" } }
],
"links": [
{ "from": "video", "to": "detector" },
{ "from": "detector", "to": "events" },
{ "from": "events", "to": "webhook" }
]
}
}
Check it:
$ python -m juturna validate --config pipeline.json
Run it¶
The events need somewhere to go. This small server prints the body of every
request it receives; save it as listener.py and start it in a terminal:
"""Print the body of every POST request received on 127.0.0.1:8080."""
import http.server
class _Handler(http.server.BaseHTTPRequestHandler):
def do_POST(self): # noqa: N802 (name set by BaseHTTPRequestHandler)
length = int(self.headers.get('Content-Length', 0))
print(self.rfile.read(length).decode(), flush=True)
self.send_response(200)
self.end_headers()
def log_message(self, format, *args): # noqa: A002
pass
if __name__ == '__main__':
server = http.server.HTTPServer(('127.0.0.1', 8080), _Handler)
print('listening on http://127.0.0.1:8080', flush=True)
server.serve_forever()
$ python listener.py
listening on http://127.0.0.1:8080
Then, in a second terminal, run the pipeline:
$ python -m juturna launch --config pipeline.json --auto --timeout 15
On the first run the detector downloads YOLOX nano (3.7 MB) into
$XDG_CACHE_HOME/juturna/models/ (~/.cache/juturna/models/ by
default). The video lasts 9 seconds, but the end of a
file does not stop the pipeline: --timeout 15 stops it after 15 seconds.
What comes out¶
The listener prints one JSON message per event, about 30 for this video. This is the first one of a real run:
{"created_at": 1794866962.8509357, "creator": "events", "version": 0, "id": 7, "payload": {"event": "detection", "label": "car", "count": 4, "objects": [{"confidence": 0.872, "bbox": [322, 476, 902, 718]}, {"confidence": 0.854, "bbox": [2, 481, 156, 585]}, {"confidence": 0.546, "bbox": [766, 495, 967, 601]}, {"confidence": 0.481, "bbox": [866, 502, 1198, 713]}], "frame": 0, "timestamp": 1794866962.835211, "width": 1280, "height": 720}, "meta": {"pipe_id": "video_detection_01"}, "timers": {}}
The event is in payload: four cars in the first frame, each with its
score and its box in pixels (x1, y1, x2, y2). The other fields are the
message envelope, which NotifierHTTP sends whole, with the pipeline id
in meta. The same frame also gives events for traffic light and
person, and each class comes back at most every 2 seconds.
When the detector falls behind¶
If the detector takes longer per frame than the source sends them, the
frames wait in its input queue, which holds 999 messages
(JUTURNA_MAX_QUEUE_SIZE). Once it is full, the source’s own queue fills
next, and then the source waits for room. Every waiting frame stays in
memory: 999 frames of 1280x720 RGB are about 2.7 GB per queue. Juturna does
not drop frames to catch up: the events come later and later than the
video. Lower fps to keep the detector in step
(Nodes tells how the queues work).
When the webcam is unplugged or its stream ends, VideoCapture fails, the error is logged and
counted in the node health, and the node opens the device again after a
pause that doubles at each failure, up to 5 seconds.
What to change¶
The input. Point
sourceto your own video, or to a webcam:"/dev/video0"(Linux only). A webcam has no end: runlaunchwithout--auto --timeout 15, and it waits for enter to start the pipeline and again to stop it.A network camera. Replace
VideoCapturewith VideoRtp, which receives an RTP stream sent torec_hostandrec_port, in thecodecgiven ("vp8"by default). It does not connect to the camera: something has to send the stream to it, and it does not limit the frame rate. When the stream stops,VideoRtpopens it again and waits for it to come back; on other errors it logssource unavailableand tries again after 2 seconds.The classes. Add
"targets": ["person", "car"]to the detector to keep only some of the 80 COCO classes, and raiseconfidence(0.3 by default) to drop the weaker detections.The model.
yolox_tinyandyolox_sare larger and more accurate; any YOLOX model exported to ONNX works too, given its path.The sink. Change
endpointto your service. NotifierConsole prints the events on the terminal instead, with no listener to run, and NotifierUDP sends them over UDP, in chunks. The catalogue lists the other sinks.A node of your own. To count objects across frames, draw boxes or write events to a database, follow Write and package a node.