How to pass image data from javascript to opencv c++ webassembly
I'm trying to pass image bufferArray to c++ function but OpenCV throw an unknown exception(test_wasm.js:2028 Uncaught).
I am beginner.
I'm trying to do the same with the help of this question.
Javascript code:
var openFile = function (e) {
const fileReader = new FileReader();
fileReader.onload = (event) => {
const uint8Arr = new Uint8Array(event.target.result);
passToWasm(uint8Arr);
};
fileReader.readAsArrayBuffer(e.target.files[0]);
};
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
console.log(dataOnHeap.byteOffset);
const res = Module._image_input(dataOnHeap.byteOffset, uint8ArrData.length);
Module._free(dataPtr);
}
Html code
<input type='file' id='img' accept='image/*' onchange='openFile(event)'>
C++ code
int image_input(uint8_t *buffer, size_t size){
cv::Mat raw_data = cv::Mat(1, size, CV_8UC1, buffer);
cv::cvtColor(raw_data, raw_data, cv::COLOR_RGB2GRAY);
return 1;
}
I also tried different colorspace. like: cv::COLOR_RGBA2GRAY, cv::COLOR_BGR2GRAY
but all are not working.
Please help.
i've no clue about wasm/js but already your c++ code won't work as intended.
cvtColor()
will reallocateraw_data
, so the result is no more inbuffer
please try to explain, what your code is supposed to do, what do you try to read frm disk, exactly ? how do you plan to manage memory ? (aka: who owns what ?)
Actually I want to pass an image from the browser to web assembly(compiled OpenCV code to web assembly) and change the colorspace and return the image in javascript.
if your FileReader is just reading an image file straight from disk, you will need an
imdecode()
step (it's NOT an image, so far) inbetween.you probably also cannot reuse the input buffer, because sizes will be different