Mat.fromBuffer constructor

Mat.fromBuffer(
  1. int rows,
  2. int cols,
  3. MatType type,
  4. Pointer<Void> buff,
)

Create a Mat from self-allocated buffer

data should be raw pixels values with exactly same length of channels * rows * cols

Be careful when using this constructor, as you are responsible for managing the native pointer yourself. Improper handling may lead to memory leaks or undefined behavior.

The resulting Mat shares the memory of buff (no copy is made): buff must be at least rows * cols * elemsize bytes and must remain valid (not freed or reused) for as long as the Mat is used. Calling Mat.dispose releases the Mat header but does not free buff.

This function can throw exception, so make sure to free the allocated memory inside a try-finally block!

Mat (int rows, int cols, int type, void *data, size_t step=AUTO_STEP)

https://docs.opencv.org/4.x/d3/d63/classcv_1_1Mat.html#a51615ebf17a64c968df0bf49b4de6a3a

Implementation

factory Mat.fromBuffer(int rows, int cols, MatType type, ffi.Pointer<ffi.Void> buff) {
  final p = calloc<cvg.Mat>();
  try {
    cvRun(() => ccore.cv_Mat_create_6_no_copy(rows, cols, type.value, buff, p, ffi.nullptr));
  } catch (_) {
    calloc.free(p);
    rethrow;
  }
  return Mat._(p); // external data is not managed by OpenCV
}