cv.Mat is not a constructor opencv

  1. Make sure that the script is really loaded. If the error is "cv is not defined", then either remove the async in the script tag or add this (or just an onload attribute in the <script> tag)

     script.addEventListener('load', () => {
    
  2. In the WASM build (and only the WASM build), cv will not be immediately available because WASM is compiled in runtime. Assign the start function to cv.onRuntimeInitialized.

    Note that the WASM version should be faster; however, it incurs some start overhead (a few CPU seconds). The non-WASM doesn't call onRuntimeInitialized at all.

    To check both cases, it's possible to do this

    if (cv.getBuildInformation)
    {
        console.log(cv.getBuildInformation());
        onloadCallback();
    }
    else
    {
        // WASM
        cv['onRuntimeInitialized']=()=>{
            console.log(cv.getBuildInformation());
            onloadCallback();
        }
    }
    

Source:

  • https://answers.opencv.org/question/207288/how-can-i-compile-opencvjs-so-that-it-does-not-require-defining-the-onruntimeinitialized-field/
  • https://docs.opencv.org/master/utils.js

I had the exact same issue here. My solution was different to the one suggested. It has more flexibility since your operations will not be limited to a certain method called in the beginning of your code.

Step 1: and it's a very important one, since it actually affected my code: Make sure there are no unrelated errors on loading the page. It disrupted the loading of opencv.js

Step 2: make sure you load the script synchronously.

<script src="<%= BASE_URL %>static/opencv.js" id="opencvjs"></script> 

That was it for me. It worked perfectly from that point.


opencv.js loads and fires the onload event before it's really initialized. To wait until opencv.js is really ready, opencv.js provides a on hook "onRuntimeInitialized". Use it something like this:

function openCvReady() {
  cv['onRuntimeInitialized']=()=>{
    // do all your work here
  };
}