如何将图像帧相机传递给wasm (C++)中的函数?

How to pass image frames camera to a function in wasm (C++)?

本文关键字:C++ 函数 wasm 图像 相机      更新时间:2023-10-16

我正在尝试构建一个C++函数并使用Emscripten将其编译为Wasm。
此函数将要做的是接收图像并对其执行一些处理并返回结果。
我的第一个 POC 成功,用户使用file输入上传图像,我使用 API 传递图像的数据FileReader

const fileReader = new FileReader();
fileReader.onload = (event) => {
const uint8Arr = new Uint8Array(event.target.result);
passToWasm(event.target.result);
};
fileReader.readAsArrayBuffer(file); // I got this `file` from `change` event of the file input.

但是当我实现相机馈送并开始获取帧以将其传递给 Wasm 时,我开始C++端出现异常,这是 JS 实现:

let imageData = canvasCtx.getImageData(0, 0, videoWidth, videoHeight);
var data=imageData.data.buffer;
var uint8Arr = new Uint8Array(data);
passToWasm(uint8Arr);

这C++方面抛出了一个异常。

现在passToWasm实现是:

function passToWasm(uint8ArrData) {
// copying the uint8ArrData to the heap
const numBytes = uint8ArrData.length * uint8ArrData.BYTES_PER_ELEMENT;
const dataPtr = Module._malloc(numBytes);
const dataOnHeap = new Uint8Array(Module.HEAPU8.buffer, dataPtr, numBytes);
dataOnHeap.set(uint8ArrData);
// calling the Wasm function
const res = Module._myWasmFunc(dataOnHeap.byteOffset, uint8ArrData.length);
}

虽然C++实现将是这样的:

void EMSCRIPTEN_KEEPALIVE checkImageQuality(uint8_t* buffer, size_t size) {
// I'm using OpenCV in C++ to process the image data
// So I read the data of the image
cv::Mat raw_data = cv::Mat(1, size, CV_8UC1, buffer);
// Then I convert it
cv::Mat img_data = cv::imdecode(raw_data, cv::IMREAD_COLOR | cv::IMREAD_IGNORE_ORIENTATION);
// in one of the following steps I'm using cvtColor function which causes the issue for some reason
}

由于相机实现,我得到的异常说:

OpenCV(4.1.0-dev) ../modules/imgproc/src/color.cpp:182:错误:(-215:断言失败)函数'cvtColor'中的!_src.empty()

使用file输入和获取数据传递它,以及从canvas获取数据,只要两者都将其转换为Uint8Array

我为此找到了解决方案(也许只适合我的情况)。
当您尝试从canvas获取图像数据时,您可以将其作为 4 个通道(RGBA 如 PNG 中),并且根据您的图像处理代码,您需要处理它。
我的代码考虑到图像应该是 3 个通道(RGB 如 jpeg),所以我不得不使用以下代码进行转换:

canvasBuffer.toBlob(function (blob) {
passToWASM(blob);
},'image/jpeg');