title: cv::imdecode an image from JS to C++ (opencv, emscripten)
body: <p>What I'm trying to do:</p>
  
  <ul>
  <li>the user loads an image in html</li>
  <li>opencv receives that image in C++ and do some work on it.</li>
  </ul>
  
  <p>What I've done is more or less the same as described here :</p>
  
  <p><a href="https://answers.opencv.org/question/222994/how-to-pass-image-data-from-javascript-to-opencv-c-webassembly/" rel="nofollow noreferrer">https://answers.opencv.org/question/222994/how-to-pass-image-data-from-javascript-to-opencv-c-webassembly/</a></p>
  
  <p>Here is the javascript part (verbatim from the given link):</p>
  
  <pre><code>var openFile = function (e) {
      const fileReader = new FileReader();
      fileReader.onload = (event) =&gt; {
          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);
  }
  </code></pre>
  
  <p>And here is the C++ part (almost verbatim):</p>
  
  <pre><code>int image_input(int offset, size_t size) //query image input
      {
        uint8_t* pos;
         pos = reinterpret_castw&lt;uint8_t*&gt;(offset);
          cv::Mat raw_data = cv::Mat(1, size, CV_8UC1, pos);
           cout &lt;&lt; raw_data &lt;&lt; endl;
          img_object = cv::imdecode(raw_data, cv::IMREAD_GRAYSCALE);
          cout &lt;&lt; img_object &lt;&lt; endl;
      }
  </code></pre>
  
  <p>When I test with some jpg images, the <code>raw_data</code> on the C++ part and the <code>uint8ArrData</code> on the JS part contain the same information: that is a list of 15253 numbers like</p>
  
  <pre><code>[255, 216, 255, 224, ..., 184, 227, 255, 217]
  </code></pre>
  
  <p>Now, the line</p>
  
  <pre><code>img_object = cv::imdecode(raw_data, cv::IMREAD_GRAYSCALE);
  </code></pre>
  
  <p>returns an empty matrix <code>[]</code>.</p>
  
  <p>What do I do wrong ?
  Do I have to make some pre-processing on the JS side ?</p>