# `BB.Inference.OpenCV`
[🔗](https://github.com/beam-bots/bb_inference_opencv/blob/main/lib/bb/inference/open_cv.ex#L5)

A `BB.Inference.Runtime` that runs ONNX models through OpenCV's DNN module,
via `evision`.

    model :detector do
      runtime BB.Inference.OpenCV
      source "https://github.com/Megvii-BaseDetection/YOLOX/releases/download/0.1.1rc0/yolox_nano.onnx"
      sha256 "c789161ed43c8269fcd4e67c67eeeb4e80c622da2eb296a20bc6007bd18a0b7d"
      codec BB.Estimator.Yolo.YoloX
    end

## What `describe/1` can and can't report

OpenCV has no API for a network's declared inputs. `getLayerShapes` only
reports shapes for inputs you have already supplied, and raises on the
arguments evision passes; the layer list has no named input layer. The one
place the declared inputs and outputs appear is the text of
`Evision.DNN.Net.dump/1`:

    "images" // <Input> CV_32FC1 [1 x 3 x 416 x 416]

so `describe/1` parses it. That gives names, element types and shapes, in
the order the graph declares them. It is a debugging format, not an API,
and may change between OpenCV versions; if it does, `describe/1` returns
tensors it couldn't read with `nil` fields rather than guessing, and a codec
will refuse to fit.

It can't report:

- **quantisation** - always `nil`. OpenCV's ONNX importer handles quantised
  graphs internally and exposes no scale or zero point.
- **layout** - always `nil`. ONNX has no layout annotation; NCHW is a
  convention, and codecs infer it from the shape.

A dimension the graph leaves dynamic is `nil`. Tested against OpenCV 5.1
through evision 1.1.

## Results

Outputs come back from OpenCV on `Evision.Backend` and are moved to
`Nx.BinaryBackend` before they are returned, which costs around 0.03ms for a
megabyte, so that a codec can read them without evision.

## Options

- `:backend` - an OpenCV DNN backend id, such as
  `Evision.Constant.cv_DNN_BACKEND_OPENCV/0`. Defaults to OpenCV's choice.
- `:target` - an OpenCV DNN target id, such as
  `Evision.Constant.cv_DNN_TARGET_CPU/0`. Defaults to OpenCV's choice.
  OpenCV 5's new graph engine ignores it, with a warning on standard
  error.

OpenCV falls back to the CPU without saying so when a backend or target
isn't available, so `can?({:accelerator, _})` is always `false`.

---

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