Ask Your Question

Revision history [back]

Convert OpenCV.js to a Wasm module to pass to web worker

To be able to pass OpenCV.js to a web worker in the WebWorker.postMessage() method, we need OpenCV as an ArrayBuffer. See this post for details.

I was able to extract the WASM code from OpenCV.js file following this post, but then I can not generate a WASM module. I copy the code I'm trying to run in a node.js program.

// Error returned by the script
Wasm decoding failed: expected magic word 00 61 73 6d

// Code executed in Node.js
const base64 = require('./opencv.wasm').wasmBinaryFile;
const buffer = base64ToArrayBuffer(base64);
const wasmModule = new WebAssembly.Module(buffer);

function base64ToArrayBuffer(base64) {
  var binary_string = new Buffer(base64).toString('base64');
  var len = binary_string.length;
  var bytes = new Uint8Array(len);
  for (var i = 0; i < len; i++) {
    bytes[i] = binary_string.charCodeAt(i);
  }
  return bytes.buffer;
}

 // file opencv.wasm with the contents of OpenCV.js wasm code (only a fraction of the base64 string is displayed)
 exports.wasmBinaryFile="data:application/wasm;base64,AGFzbQ ...... ";

How is the correct way to pass OpenCV.js to a web worker or how can a wasm module be created from OpenCV.js?