# `BB.Estimator.ObjectDetection.Image`
[🔗](https://github.com/beam-bots/bb_estimator_object_detection/blob/main/lib/bb/estimator/object_detection/image.ex#L5)

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 `c:BB.Inference.ModelCodec.options_schema/0`:

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

In `c:BB.Inference.ModelCodec.fit/2` it builds a spec from the model's
input tensor with `spec/2`, and in `c: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.

# `options_schema`

```elixir
@spec options_schema(keyword()) :: keyword()
```

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

# `prepare`

```elixir
@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`

```elixir
@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.

# `to_frame`

```elixir
@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.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
