Welcome back
You left off at . Pick up where you were, or start over from the beginning.
Glossary
Subscribe
Can I cancel anytime?
Yes — cancel anytime from your Account page. Cancellation takes effect immediately.
Do you offer refunds?
We don't offer prorated refunds for the unused portion of a billing period, unless required by law in your billing country. You keep access until you cancel.
What happens if my payment fails?
You keep access during a short grace period while the payment is retried. If it still hasn't succeeded by the end of that period, access stops until you resubscribe.
Report an issue
Sends a message straight to our support inbox — we'll reply to your account email.
AI code review
Account blocked
Your account has been blocked and can no longer sign in. If you believe this is a mistake, please contact support.
Translate this chapter
Translates the workbook's prose only — code, formulas, diagrams, and images/GIFs stay in English. Machine-translated, may be imperfect; refer to the English original for anything technical.
Real-Time Vision AI
with swatahVision
Detection, tracking & analytics pipelines you can actually ship.
A hands-on field guide to the open-source swatahVision stack from VisionAI4Bhārat — one Python API across ONNX, OpenVINO, TFLite and RKNN, built directly from the project's own docs and examples. No paywall, no signup required.
Why a Unified Vision AI Stack
Every real computer-vision product needs the same six pieces of plumbing before it does anything useful. swatahVision's whole reason for existing is to stop you from rebuilding that plumbing on every project. This chapter maps the pipeline you'll spend the rest of the course filling in.
A vision model isn't "done" when it hits a good mAP number on a benchmark — it's done when it runs at a usable frame rate on the exact device sitting in your product, and someone besides you can read the code six months later.
1.1 · The stack nobody wants to rewrite
Say you want to build something as simple as "count how many people walk past this camera." The actual object-counting logic is maybe ten lines. Everything else is plumbing: loading a model file into some inference engine, decoding a tensor of raw numbers into boxes you can reason about, filtering out the duplicate boxes every detector produces, keeping track of which box in frame 40 is the same person as a box in frame 39, and finally drawing something a human can look at. That plumbing is almost identical whether you're counting people, cars, or boxes on a conveyor belt — yet most teams write it from scratch every time.
swatahVision is VisionAI4Bhārat's open-source answer: a single Python package that owns that plumbing, so your project code can start at the ten interesting lines instead of the two hundred boring ones.
Inference
One Model() wrapper that runs the same way whether the file underneath is ONNX, OpenVINO, TFLite, or RKNN.
Post-processing
YOLO, SSD, and RetinaNet decoders plus NMS/NMM baked in, so raw tensors become a clean Detections object.
Tracking
ByteTrack gives every object a stable tracker_id that survives from frame to frame.
Visualization
Annotators turn boxes, labels, traces, and heatmaps into pixels — no manual OpenCV drawing code.
runs inference
decoded + NMS'd
assigns IDs
draws pixels
count, alert, log
The core package is licensed under LGPL-3.0 — free to use, including commercially, as long as you respect the library-linking terms. Separate commercial add-ons exist for enterprise deployment tooling, but nothing in this course requires them.
Why bake NMS and tracking into the library instead of leaving every project to write its own?
Which of these is not something swatahVision does today: (a) decode raw YOLO output into boxes, (b) train a new detection model from scratch, (c) draw a bounding box on a frame?
- Before writing any code, sketch on paper the boxes-and-arrows pipeline for a real idea of your own (e.g. "count cars in a parking lot," "alert if someone enters a restricted zone"). Label which boxes are swatahVision's job and which are yours.
- List three vision projects where you would not need a tracker at all — only detection or classification. What do they have in common?
- Skim the project's GitHub repo and find one module this course doesn't cover (hint: look under
swatahvision/geometryorswatahvision/utils). Write two sentences on what it does.
Installing swatahVision & Your First Inference
Requires Python 3.12+. Two lines to install, three objects to learn: Model, Engine, and Hardware. Everything in this course builds on getting these three right.
pip install swatahVisionFastest path. Pin a version if you want reproducible installs: pip install swatahVision=="1.1.*".
git clone https://github.com/VisionAI4Bharat/swatahVision.git cd swatahVision pip install -e .
Editable install — pulls in the examples/ and model_zoo/ folders alongside the package, useful while working through this course.
2.1 · Your first inference call
Every model in swatahVision, no matter which runtime it's stored as, is loaded and called the same way:
import swatahVision as sv model = sv.Model( model="yolov8n-640.onnx", engine=sv.Engine.ONNX, hardware=sv.Hardware.CPU ) image = sv.Image.load_from_file("street.jpg") outputs = model(image) print(type(outputs))
Load an image
sv.Image.load_from_file(path) hands back something the model can consume — no manual OpenCV/PIL juggling.
Build a Model
Three arguments: the model file, which Engine reads it, which Hardware runs it.
Call it
model(image) — the wrapper is callable directly; under the hood it dispatches to the right runtime's infer().
Get raw output
What comes back is still just numbers — raw tensors. Chapters 3–5 turn that into Detections or Classification.
| Engine member | Underlying runtime |
|---|---|
Engine.ONNX | ONNX Runtime |
Engine.OPENVINO | Intel OpenVINO |
Engine.TFLITE | TensorFlow Lite |
Engine.RKNN | Rockchip NPU (RKNN) |
Engine.PYTORCH | Native PyTorch / remote inference |
| Hardware member | Meaning |
|---|---|
Hardware.CPU | Run on the local CPU |
Hardware.GPU | Run on a local GPU |
Hardware.NPU | Run on a dedicated neural accelerator |
Hardware.REMOTE | Dispatch inference to a remote server |
model = sv.Model(
model="yolov8n-640.onnx",
engine=sv.Engine.ONNX,
hardware=sv.Hardware.CPU
)
RKNN only makes sense on Rockchip NPUs; OpenVINO's GPU path expects an Intel iGPU. Mismatch them and you'll get a runtime error, not a silent fallback — check Chapter 6 before picking a combination for production.
- Install swatahVision and run the quickstart above against any small image. Print the raw output's shape.
- Swap
hardware=sv.Hardware.CPUforsv.Hardware.GPU— what would you expect to happen on a machine with no GPU?
The Detections Object
Detections is the single data structure nearly every other part of swatahVision consumes or produces. Get comfortable with its shape now and the rest of the course reads much faster.
A Detections object doesn't wrap one detected object — it wraps all of them from one frame, as parallel arrays. Detection i's box is xyxy[i], its confidence is confidence[i], and so on.
| Field | Description |
|---|---|
xyxy | Bounding box coordinates [x1, y1, x2, y2] |
confidence | Detection confidence score |
class_id | Predicted object class |
mask | Segmentation mask (optional) |
tracker_id | Object tracking ID (optional, set by a tracker — Chapter 8) |
data / metadata | Anything else you attach yourself |
import numpy as np import swatahVision as sv detections = sv.Detections( xyxy=np.array([[50, 60, 200, 220]]), confidence=np.array([0.89]), class_id=np.array([1]) ) print(len(detections)) # 1 print(detections.xyxy[0]) # [50 60 200 220]
Filtering, slicing, and combining
# slice like a list first_five = detections[0:5] # filter with a boolean mask high_conf = detections[detections.confidence > 0.6] persons = detections[detections.class_id == 0] # combine results from two different models merged = sv.Detections.merge([detections1, detections2]) # the empty case, useful as a safe default empty = sv.Detections.empty() empty.is_empty() # True
Several tools (zone counting in Chapter 9, for one) don't care about the whole box — just one reference point on it, called its anchor position. get_anchors_coordinates(Position.X) supports CENTER, TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT, CENTER_LEFT, CENTER_RIGHT, and BOTTOM_CENTER.
You want a zone-counting event to fire when a person's feet cross into a zone, not when their head enters the top of frame. Which anchor position should you trigger on?
Position.BOTTOM_CENTER — the bottom-middle of the box tracks close to where feet actually are. It's exactly why PolygonZone in Chapter 9 defaults to it.- Create three
Detectionsby hand with different confidences. Filter to only those above 0.5. - Merge your three detections with an empty
Detections.empty()— confirm the count doesn't change.
From Raw Tensors to Detections — Decoders, NMS & NMM
A raw model output is just an array of numbers. Turning it into a Detections object — and cleaning up the duplicate boxes every detector produces — is a two-step job.
4.1 · Decoders: raw tensor → Detections
Different model families encode their predictions differently, so each gets its own decoder function:
# YOLO-style output detections = sv.Detections.from_yolo(outputs, conf_threshold=0.3, nms_threshold=0.5, class_agnostic=False) # SSD-style output detections = sv.Detections.from_ssd(outputs, conf_threshold=0.5) # RetinaNet-style output detections = sv.Detections.from_retinanet(outputs, conf_threshold=0.5)
4.2 · Why you get duplicates in the first place
Detectors like YOLO evaluate a dense grid of candidate locations, so a single real object almost always triggers several overlapping, slightly-different boxes around it. Non-Maximum Suppression (NMS) throws away all but the highest-confidence box in each overlapping cluster. Non-Maximum Merging (NMM) takes the opposite approach — instead of discarding the overlapping boxes, it fuses them into one combined box.
filtered = detections.with_nms(threshold=0.5, class_agnostic=False) merged = detections.with_nmm(threshold=0.5)
Too low, and boxes for two people standing close together get merged into one. Too high, and you keep duplicate boxes for a single object. There's no universal correct value — it depends on how crowded your scenes typically are.
- By hand: four boxes around the same object have confidences 0.91, 0.87, 0.65, 0.52 and all overlap heavily. At an IoU threshold of 0.5, which survive plain NMS?
- Describe a scene where NMM's "merge" behavior is more appropriate than NMS's "remove" behavior.
Classification Outputs
Classification asks a simpler question than detection — "what is the whole image?" rather than "what's in it and where?" The Classification class standardizes that answer across model families.
Whether the underlying model is MobileNet or ResNet, the output always normalizes to the same two arrays: class_id and confidence. Softmax is applied automatically if the model handed back raw logits instead of probabilities — you don't normalize anything yourself.
result = sv.Classification.from_mobilenet(mobilenet_output, top_k=1) print(result.class_id, result.confidence) # [5] [0.94] result = sv.Classification.from_resnet(resnet_output, top_k=3) print(result.class_id, result.confidence) # [[3 7 1]] [[0.88 0.07 0.02]]
| Attribute | Type | Description |
|---|---|---|
class_id | np.ndarray | Predicted class index (or indices, for top-k) |
confidence | np.ndarray | None | Probability score per prediction |
What happens if you request top_k=50 but the model only outputs 10 classes?
ValueError: top_k cannot be greater than number of classes — it fails loudly rather than silently padding or wrapping.What input shape does from_mobilenet/from_resnet expect the raw model output to be?
(B, C) — a batch dimension and a class-score dimension. Anything else raises ValueError: Invalid output shape.- Run the same classification output through
top_k=1andtop_k=3— confirm the top-1 result is always the first entry of the top-3 result.
Choosing a Runtime & Hardware
The Model() call never changes shape — only the engine and hardware arguments do. The real skill is picking the pairing that matches where your code will actually run.
| Engine | Typical hardware | Best for |
|---|---|---|
| ONNX | CPU, GPU | Broadest compatibility — the default most model zoos ship first |
| OpenVINO | Intel CPU / iGPU | Intel-based edge boxes and retail hardware |
| TFLite | Mobile / embedded CPU | Android, iOS, Raspberry Pi |
| RKNN | Rockchip NPU | Rockchip single-board computers (e.g. RK3588) |
| PyTorch / Remote | Hardware.REMOTE | Delegating inference to a server instead of running locally |
# same call, three different targets — only two args change sv.Model(model="m.onnx", engine=sv.Engine.ONNX, hardware=sv.Hardware.GPU) sv.Model(model="m.xml", engine=sv.Engine.OPENVINO, hardware=sv.Hardware.CPU) sv.Model(model="m.rknn", engine=sv.Engine.RKNN, hardware=sv.Hardware.NPU)
A synthetic benchmark on your laptop tells you almost nothing about frame rate on the actual edge box your product ships on. Measure on target hardware before you commit to an engine.
- If you have both an
.onnxand an OpenVINO.xml/.binpair for the same model, write a short script that loads both and times 100 inference calls on each withtime.perf_counter(). Compare.
Annotators — Drawing on Reality
A Detections object is still just numbers. Annotators turn those numbers into pixels a human can look at and trust.
box_annotator = sv.BoxAnnotator() label_annotator = sv.LabelAnnotator(color_lookup=sv.ColorLookup.TRACK) trace_annotator = sv.TraceAnnotator(trace_length=30) heat_annotator = sv.HeatMapAnnotator(opacity=0.3, radius=40) frame = box_annotator.annotate(scene=frame, detections=detections) frame = label_annotator.annotate(scene=frame, detections=detections, labels=labels)
| Color lookup | Boxes are colored by… |
|---|---|
INDEX | Position in this frame's detection list |
CLASS | Predicted class — every car is the same color |
TRACK | Tracker ID — a stable color per physical object across frames |
It reads detections.tracker_id to know which historical points belong to which object. Without running a tracker (Chapter 8) first, it raises ValueError: The tracker_id field is missing.
Which color_lookup strategy keeps a specific car the same color across the whole video, even as other cars enter and leave the frame?
TRACK — because it keys off tracker_id, which is stable per physical object, rather than INDEX (which shifts every frame) or CLASS (which every car of the same type shares).- Chain
BoxAnnotatorandLabelAnnotatoron one frame and save the result withcv2.imwrite.
Multi-Object Tracking with ByteTrack
Detection alone has no memory — it doesn't know that "the car in frame 40" is the same car as "the car in frame 39." ByteTrack adds that memory back, as a stable tracker_id.
Detection filtering
Split detections into high- and low-confidence groups.
First association
Match high-confidence detections to existing tracks by IoU.
Second association
Use the low-confidence leftovers to recover temporarily lost tracks.
Track initialization & removal
Unmatched detections start new tracks; tracks lost too long are removed for good.
| Parameter | Default | Meaning |
|---|---|---|
track_activation_threshold | 0.25 | Minimum confidence to start a track |
lost_track_buffer | 30 | Frames a track is kept alive after it disappears |
minimum_matching_threshold | 0.8 | IoU threshold for matching a detection to a track |
frame_rate | 30 | FPS of the video being processed |
minimum_consecutive_frames | 1 | Frames an object must persist before being a valid track |
tracker = sv.ByteTrack() for frame in sv.get_video_frames_generator("input.mp4"): outputs = model(frame) detections = sv.Detections.from_yolo(outputs, conf_threshold=0.3) detections = tracker.update_with_detections(detections) labels = [f"#{tid}" for tid in detections.tracker_id] frame = box_annotator.annotate(scene=frame, detections=detections) frame = label_annotator.annotate(scene=frame, detections=detections, labels=labels)
tracker.reset() clears tracked/lost/removed state. Call it between separate video files — otherwise IDs from the last clip can bleed into the next one.
You set lost_track_buffer=60 on a 30fps video. What real-world occlusion duration does that tolerate before an object gets a brand-new ID instead of keeping its old one?
tracker_id.- What would you expect to happen to
tracker_idstability if you setminimum_matching_thresholdextremely low, e.g. 0.1?
Lab — Counting People in Zones
Your first full lab, adapted directly from the project's own examples/count_people_in_zone script: draw a polygon over part of the frame and count how many people are inside it, right now.
import json import numpy as np import swatahVision as sv def load_zones(path): with open(path) as f: return [np.array(p, np.int32) for p in json.load(f)["polygons"]] polygons = load_zones("zone_configuration.json") zones = [sv.PolygonZone(polygon=p) for p in polygons] zone_annotators = [sv.PolygonZoneAnnotator(zone=z, color=sv.ColorPalette.DEFAULT.by_idx(i)) for i, z in enumerate(zones)] box_annotator = sv.BoxAnnotator() def detect_people(frame, model, conf=0.5): outputs = model(frame) detections = sv.Detections.from_yolo(outputs) return detections[(detections.class_id == 0) & (detections.confidence > conf)] for frame in sv.get_video_frames_generator("input.mp4"): detections = detect_people(frame, model) for zone, zone_annotator in zip(zones, zone_annotators): in_zone = detections[zone.trigger(detections=detections)] frame = zone_annotator.annotate(scene=frame) frame = box_annotator.annotate(scene=frame, detections=in_zone)
| Constructor param | Where | Meaning |
|---|---|---|
polygon, triggering_anchors | PolygonZone | The zone shape, and which box anchor must fall inside it |
display_in_zone_count, opacity | PolygonZoneAnnotator | Whether to draw the live count label, and zone fill transparency |
Polygon coordinates are plain pixel coordinates matching your video's resolution. Pause a frame, read off corner pixel positions, and use those — don't guess.
If you set triggering_anchors=(Position.CENTER,) instead of the default BOTTOM_CENTER, how would a person walking through a doorway register differently?
- Split one wide zone into two side-by-side polygons (e.g. left half / right half of a hallway) and count each independently.
- Track
zone.current_countacross an entire video and report the single highest value seen — a "peak occupancy" metric, not just the current-frame count.
Lab — Traffic Analysis, Speed Estimation & Heatmaps
This lab stacks nearly everything so far — detection, ByteTrack, and two annotators — into one traffic-monitoring pipeline, then adds a DIY technique for estimating speed.
sv.SpeedEstimatorUnlike detection or tracking, speed estimation isn't a single library call — it's a pattern you build yourself on top of tracker_id positions and a known real-world distance, exactly like the project's own example script does: timestamp when a tracked object crosses two reference lines a known distance apart, then distance ÷ time.
tracker = sv.ByteTrack() trace_annotator = sv.TraceAnnotator(trace_length=30) heat_annotator = sv.HeatMapAnnotator(opacity=0.25, radius=35, top_hue=0, low_hue=125) for frame in sv.get_video_frames_generator("traffic.mp4"): detections = sv.Detections.from_yolo(model(frame), conf_threshold=0.3) detections = tracker.update_with_detections(detections) frame = box_annotator.annotate(scene=frame, detections=detections) frame = trace_annotator.annotate(scene=frame, detections=detections) frame = heat_annotator.annotate(scene=frame, detections=detections)
| HeatMapAnnotator param | Meaning |
|---|---|
opacity | Overlay transparency, 0 (invisible) to 1 (fully opaque) |
radius | Size of the heat blob added per detection |
top_hue / low_hue | HSV hue range mapping activity level to color — defaults give red for high, blue for low |
A 24-hour retail camera feed averaged into one heatmap tells you almost nothing useful — reset or snapshot it on an hourly cadence instead.
- Given a car crosses Line A at t=12.0s and Line B at t=13.4s, and the lines are 20m apart, compute its speed in km/h by hand.
Lab — Faces, Poses, Age & Gender
Three human-centric tasks from the model zoo, each just a different model file through the exact same Model() API you already know.
model = sv.Model(model="age-gender-recognition-retail-0013.xml", engine=sv.Engine.OPENVINO, hardware=sv.Hardware.CPU) image = sv.Image.load_from_file("face_crop.jpg") gender_blob, age_blob = model(image)[0] gender = "Male" if int(np.argmax(gender_blob)) == 1 else "Female" age = int(age_blob[0][0][0][0] * 100)
| Model | Task | Engine in model zoo |
|---|---|---|
| BlazeFace | Face detection | ONNX |
| MoveNet | Pose estimation (17 keypoints) | ONNX |
| age-gender-recognition-retail-0013 | Age & gender classification | OpenVINO |
They ship as an .xml/.bin pair, so remember engine=sv.Engine.OPENVINO — loading them with Engine.ONNX will fail outright.
The age/gender model expects an already-cropped face, not a full street photo. Which chapter's tool would you reach for first, in a real pipeline, to produce that crop?
Model() + Detections.from_yolo/appropriate decoder pattern from Chapters 2–4) — detect the face box first, crop the image to it, then classify age/gender on the crop.- Sketch (pseudocode is fine) a two-stage pipeline: detect faces in a full frame, then run age/gender classification on each cropped face box.
Capstone — Assemble the Full Pipeline
Everything from the last eleven chapters strings together into one loop that runs once per frame. This chapter closes the loop, then hands you a real project brief.
Targets to aim for in your own project — not published benchmarks of the library itself.
- Pick one scenario: retail queue counting, parking-lot occupancy, doorway traffic counter, or a restricted-zone alert.
- Build a pipeline using at least: detection, ByteTrack, one annotator, and one analytics module (zone counting or heatmap).
- Write a short README explaining your zone/threshold choices and any trade-offs you hit.
swatahVision's core is LGPL-3.0 — free to use, including commercially, as long as you respect the library-linking terms. Enterprise deployment tooling and OEM extensions are offered separately by swatah.ai / NeuralSense AI, but nothing here required them.
Continue learning
- GitHub repository — source, issues, and contributing guide.
- Model zoo — pretrained weights across every engine covered in this course.