BB.Estimator.ObjectDetection.Image (bb_estimator_object_detection v0.1.0)

Copy Markdown View Source

Turns a camera frame into a model's image input, and model coordinates back into frame coordinates. Every image codec calls this rather than doing its own conversion.

A codec takes the image conventions as options, with its own defaults, by merging options_schema/1 into its BB.Inference.ModelCodec.options_schema/0:

def options_schema do
  Spark.Options.new!(Image.options_schema(colour: :bgr, resize: :letterbox, pad: 114))
end

In BB.Inference.ModelCodec.fit/2 it builds a spec from the model's input tensor with spec/2, and in BB.Inference.ModelCodec.encode/2 it calls prepare/2 with the frame.

The conversion

All in OpenCV, while the image is still a matrix - doing any of it in Nx's binary backend costs hundreds of milliseconds a frame:

  1. I420 to RGB or BGR (:colour).
  2. Resize to the model's input: :stretch to fill it, or :letterbox to fit it keeping the aspect ratio, padded with grey :pad, aligned :top_left or :centre (:letterbox_align).
  3. Normalise each channel: the model sees (pixel - mean) / std, with :mean and :std given per channel in the model's channel order, or as one number for all three.
  4. Quantise, if the input tensor is quantised: real / scale + zero_point, rounded and saturated to the tensor's type.

Steps 3 and 4 are one affine step per channel, applied as OpenCV converts the element type. The result is laid out NCHW or NHWC to match the tensor's shape.

Summary

Functions

The image convention options, with defaults overriding the generic ones.

Convert a {:raw, :I420} frame into the model's input tensor, with the transform that maps the model's pixels back to the frame's.

Build a spec for preparing frames for tensor, an image input of shape {1, 3, height, width} (NCHW) or {1, height, width, 3} (NHWC), of type u8, s8 or f32. opts are the image options, validated.

Map a box in model-input pixels to frame pixels, clipped to the frame.

Functions

options_schema(defaults \\ [])

@spec options_schema(keyword()) :: keyword()

The image convention options, with defaults overriding the generic ones.

prepare(frame, spec)

Convert a {:raw, :I420} frame into the model's input tensor, with the transform that maps the model's pixels back to the frame's.

spec(tensor, opts)

Build a spec for preparing frames for tensor, an image input of shape {1, 3, height, width} (NCHW) or {1, height, width, 3} (NHWC), of type u8, s8 or f32. opts are the image options, validated.

On a tensor it can't prepare, returns a sentence saying what it expected.

to_frame(arg, transform)

@spec to_frame(
  {number(), number(), number(), number()},
  BB.Estimator.ObjectDetection.Image.Transform.t()
) :: {float(), float(), float(), float()}

Map a box in model-input pixels to frame pixels, clipped to the frame.