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))
endIn 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:
- I420 to RGB or BGR (
:colour). - Resize to the model's input:
:stretchto fill it, or:letterboxto fit it keeping the aspect ratio, padded with grey:pad, aligned:top_leftor:centre(:letterbox_align). - Normalise each channel: the model sees
(pixel - mean) / std, with:meanand:stdgiven per channel in the model's channel order, or as one number for all three. - 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
The image convention options, with defaults overriding the generic ones.
@spec prepare( BB.Message.Camera.Frame.t(), BB.Estimator.ObjectDetection.Image.Spec.t() ) :: {:ok, Nx.Tensor.t(), BB.Estimator.ObjectDetection.Image.Transform.t()} | {:error, {:unsupported_format, term()}}
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 spec(BB.Inference.Description.Tensor.t(), keyword()) :: {:ok, BB.Estimator.ObjectDetection.Image.Spec.t()} | {:error, String.t()}
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.
@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.