Aner Vision
Prepare RGB frames as NCHW tensors, retain image geometry and postprocess explicitly supplied detection rows with bounded native slots.
ImplementedAner 0.1.0 or neweraner.vision prepares video frames for numerical models and postprocesses explicitly supplied detection rows. It complements Aner Video, Tensor, neural networks and classical models.
The module includes CPU image preprocessing and box postprocessing; pretrained model import, detector execution, segmentation, tracking and cross camera identity remain future work.
Prepare one frame
import aner.video
import aner.vision
import aner.tensor
let source = video.synthetic(width: 320, height: 180, frames: 1)
let frame = video.frame_slot()
let plan = vision.preprocess(width: 224, height: 224)
let input = vision.input_slot(plan)
if source.read_into(frame) == "ready" {
plan.prepare_into(frame, input)
let images = input.tensor()
print(tensor.dim(images, 0))
print(tensor.dim(images, 1))
print(tensor.dim(images, 2))
print(tensor.dim(images, 3))
print(dtype(images))
}
source.close()Output has shape [1, 3, height, width], NCHW layout, Float32 dtype and CPU placement. It is detached from automatic differentiation. Capture and preprocessing do not train a model. Retain the immutable plan and reuse the mutable input slot for subsequent frames.
Geometry
resize | Behavior | Use |
|---|---|---|
letterbox | Preserve aspect ratio, resize to fit, pad the remaining area | Models trained with padded geometry |
stretch | Resize width and height independently | Models trained on directly resized inputs |
crop | Preserve aspect ratio, resize to cover, center crop | Models trained with center crop inference |
Choose the policy required by the model's training recipe. Letterboxing is a default, not a universally correct transform. Odd padding/cropping favors the right/bottom side. Pixel coordinate mapping uses the actual integer resized dimensions and offsets.
For a non padding output pixel x, the source sample coordinate is (x - offset_x + 0.5) / scale_x - 0.5, and similarly for y. filter: "bilinear" interpolates between these half pixel centers with clamped edge samples. "nearest" clamps the source coordinate and selects floor(coordinate + 0.5). The initial format is RGB8: there is no implicit BGR swap, grayscale expansion, alpha compositing or sensor color calibration.
Pixel normalization
For channel c, preprocessing computes:
output[c,y,x] = (RGB8[c,y,x] * scale - mean[c]) / std[c]The default scale is 1.0 / 255.0, means are zero, standard deviations are one and padding is 114.0 in the RGB8 domain before normalization. All values must be finite; channel standard deviations must be positive.
let plan = vision.preprocess(224, 224, resize: "crop")
.normalize(mean_r: 0.485, mean_g: 0.456, mean_b: 0.406,
std_r: 0.229, std_g: 0.224, std_b: 0.225)These constants illustrate one explicit normalization recipe. A checkpoint's required geometry, channel order and normalization must be supplied with that checkpoint; the module does not infer them from a filename or architecture name.
Plans are immutable. normalize returns a new plan. Each preparation allocates a replacement owned tensor; reusing an input slot bounds retained state but does not promise allocation free preprocessing. Input slots and detection sets are mutable native handles: copies alias their current contents. Preparing a new frame replaces a slot's current tensor and mapping. A previously retrieved Tensor retains its own immutable storage; retaining every tensor deliberately consumes memory.
Use one coordinated caller for each mutable input/result slot. Complete inference and supplied box postprocessing for the current input before preparing the next frame into that slot. A retained Tensor does not freeze the slot's separately mutable coordinate mapping. A different output width or height requires a new input slot; changing normalization while preserving output geometry can reuse the existing slot.
Compose with native CNNs
import aner.nn
let model = nn.cnn(channels: 3, height: 224, width: 224)
.conv2d(outputs: 4, padding: 1).relu()
.global_pool().head(classes: 2)
.on(device: "cpu", precision: "Float32").prepare()
// After plan.prepare_into(frame, input):
let scores = model.logits(input.tensor())
print(tensor.dim(scores, 0))
print(tensor.dim(scores, 1))This freshly initialized model demonstrates shape compatibility, not useful recognition. Load or fit a compatible model before evaluating recognition quality. The complete CNN example uses a small synthetic input and explicitly identifies its random weights.
GPU execution remains an explicit model/tensor placement decision. Preprocessing returns a CPU tensor; a compatible model may perform its documented placement. This increment does not provide camera to GPU zero copy, GPU preprocessing or hidden transfer free inference.
Compose with classical models
Classical aner.ml estimators consume rank two feature tensors. An image batch's NCHW dimensions are not a fitted feature schema. For a deliberate raw pixel baseline, use input.features() to make an explicit detached Float32 [1, 3 * height * width] copy and keep the same transform at fitting and prediction. KNN and K means consume these stored Float32 values through their documented CPU calculation paths; this does not provide GPU classical inference or recover discarded precision. A learned embedding is a different feature recipe and needs an explicit extractor.
import aner.tensor
import aner.ml
// With a 16 × 16 preprocessor and an existing prepared input:
let features = input.features()
// Supply a model fitted on this exact dtype, geometry and preprocessing:
// let classes = ml.predict(fitted_model, features)
print(tensor.cols(features))Do not refit preprocessing on each camera frame or mix training and evaluation observations. When building a video dataset, split by recording/session, camera or time as the research question requires; adjacent near identical frames can otherwise leak across partitions.
The complete preprocessing example also makes an explicit Float64 feature copy, fits a one row KNN and predicts that same synthetic fixture. This verifies aner.ml interoperability; it is not held out evaluation or evidence of recognition quality.
Supplied box postprocessing
vision.postprocess_into consumes already decoded detector rows. It does not interpret arbitrary neural output heads or execute a detector.
The input is a CPU Float32 or Float64 rank two Tensor with exactly six columns:
| Column | Meaning |
|---|---|
| 0 to 3 | x1, y1, x2, y2 corners in preprocessed model input pixels |
| 4 | Score in [0, 1] |
| 5 | Exact integer class ID in 0..2147483647 |
Coordinates use continuous corner geometry, with area (x2-x1)*(y2-y1) and no inclusive +1. They are not normalized coordinates or center/width/height rows. Scores are supplied model scores and are not automatically calibrated probabilities.
let detector_rows: Tensor = [
[20.0, 30.0, 120.0, 140.0, 0.9, 0.0],
[22.0, 32.0, 118.0, 138.0, 0.8, 0.0]]
let objects = vision.detections(max_detections: 100)
vision.postprocess_into(detector_rows, input, objects,
score_threshold: 0.25, iou_threshold: 0.45)
print(objects.count())
if objects.count() > 0 {
print(objects.class_id(0))
print(objects.score(0))
print(objects.x1(0))
}Every row is validated, including rows below the score threshold. Postprocessing reverses the input slot's resize/pad/crop mapping, clips to original frame boundaries and discards zero area boxes. Greedy non maximum suppression is class aware, visits descending scores and breaks equal scores by original row order. Suppression occurs when IoU is strictly greater than iou_threshold. Different classes do not suppress each other. Output count is capped by the detection set's configured capacity.
The input slot must describe the same frame that produced the detector rows. Postprocessing retains that frame's source/session/sequence identity and geometry. The caller owns this pairing: arbitrary tensors do not carry automatic capture provenance. Transfer device outputs to CPU explicitly before this operation; it performs no hidden GPU readback.
See the complete postprocessing example, which labels its rows as synthetic.
Resource and failure contracts
Plans admit output width and height in 1..4096, with at most 16,777,216 elements across the three Float32 channels. They validate dimensions and output size before allocating. Input slots retain one current prepared tensor and mapping. Detection sets admit 1..4096 retained boxes; max_candidates admits 1..65536 supplied rows, with a default of 10,000. Preprocessing scales with output pixels. NMS sorts candidates and then compares each candidate with at most the retained box capacity; when that capacity grows with candidate count, worst case work is quadratic. Set realistic limits for real time use.
Invalid preparation or postprocessing leaves the previous successfully published slot/result contents unchanged. Postprocessing can produce an empty detection set when all supplied rows are filtered or clip to zero area; ordinary Tensor constructors still require positive dimensions.
Use reusable slots and scalar detection accessors instead of constructing a new managed List of objects every frame. Native vision errors are source located R4302 diagnostics. Invalid shapes, nonfinite values, unsupported policies, incompatible frame/slot geometry, unready inputs and excessive limits fail explicitly.
The video/vision parameter reference lists signatures and defaults. Native tests cover color normalization, geometry, coordinate reversal, clipping, deterministic NMS and invalid inputs. End to end language examples establish integration mechanics; they do not establish detector accuracy, synchronized multi camera measurement or accelerator performance.
See the complete callable index for the native module and method name catalogue.