簡體   English   中英

如何將圖像幀相機傳遞給 wasm (C++) 中的函數?

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

我正在嘗試構建一個 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++ 端拋出異常。

現在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: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'

使用file輸入和獲取數據來傳遞它和從canvas獲取數據之間有什么區別,只要它們都將其轉換為Uint8Array

我找到了一個解決方案(也許只適合我的情況)。
當您嘗試從canvas獲取圖像數據時,您將獲得 4 個通道(如 PNG 中的 RGBA),並且根據您需要處理的圖像處理代碼。
我的代碼考慮到圖像應該是 3 個通道(像 jpeg 中的 RGB)所以我不得不使用以下代碼轉換它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM