我正在尝试构建一个 C++ 函数并使用 Emscripten 将其编译为 Wasm。
该函数的作用是接收图像并对其进行一些处理并返回结果。
我的第一个 POC 成功了,用户使用上传图像file
输入,我使用传递图像的数据FileReader
API:
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++ 端引发异常。
Now 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:断言失败) !_src.empty() 在函数“cvtColor”中
使用有什么区别file
输入并获取数据以传递给它,并从 a 获取数据canvas
只要它们都将其转换为Uint8Array