matFromPackedBytes function
Rebuilds a tightly packed cv.Mat from raw bytes with a single memcpy.
cv.Mat.fromList routes every byte through a lazy cast<int> view and
copies element-by-element (~8 ms for a 1080p BGR frame); allocating the
Mat and copying into its native buffer is two orders of magnitude faster.
Only valid for tightly packed (continuous) pixel data.
Throws ArgumentError if bytes does not match rows x cols x elemSize
for type.
Implementation
cv.Mat matFromPackedBytes(
int rows,
int cols,
cv.MatType type,
Uint8List bytes,
) {
final cv.Mat mat = cv.Mat.create(rows: rows, cols: cols, type: type);
final Uint8List dst = mat.data;
if (dst.length != bytes.length) {
final int expected = dst.length;
mat.dispose();
throw ArgumentError(
'bytes.length ${bytes.length} does not match a '
'$rows x $cols Mat of type $type ($expected bytes)',
);
}
dst.setAll(0, bytes);
return mat;
}