convertImageToTensor function

ImageTensor convertImageToTensor(
  1. Mat src, {
  2. required int outW,
  3. required int outH,
  4. Float32List? buffer,
})

Converts a cv.Mat image to a normalized float32 tensor with letterboxing.

Performs aspect-preserving resize with black padding and normalizes pixel values to the [-1.0, 1.0] range expected by EfficientDet float32/float16 models (mean=127.5, std=127.5). Channel order is BGR→RGB.

The input cv.Mat is NOT disposed by this function.

Implementation

ImageTensor convertImageToTensor(
  cv.Mat src, {
  required int outW,
  required int outH,
  Float32List? buffer,
}) {
  final int inW = src.cols;
  final int inH = src.rows;

  final LetterboxParams lbp = computeLetterboxParams(
    srcWidth: inW,
    srcHeight: inH,
    targetWidth: outW,
    targetHeight: outH,
  );

  final cv.Mat resized = cv.resize(
    src,
    (lbp.newWidth, lbp.newHeight),
    interpolation: cv.INTER_LINEAR,
  );

  final cv.Mat padded = cv.copyMakeBorder(
    resized,
    lbp.padTop,
    lbp.padBottom,
    lbp.padLeft,
    lbp.padRight,
    cv.BORDER_CONSTANT,
    value: cv.Scalar.black,
  );
  resized.dispose();

  final Float32List tensor = bgrBytesToSignedFloat32(
    bytes: padded.data,
    totalPixels: outW * outH,
    buffer: buffer,
  );
  padded.dispose();

  final double padTopNorm = lbp.padTop / outH;
  final double padBottomNorm = lbp.padBottom / outH;
  final double padLeftNorm = lbp.padLeft / outW;
  final double padRightNorm = lbp.padRight / outW;

  return ImageTensor(
    tensor,
    [padTopNorm, padBottomNorm, padLeftNorm, padRightNorm],
    outW,
    outH,
  );
}