首页 > 解决方案 > 无法从函数访问 opencv.js 属性和方法

问题描述

html我使用托管的 o​​pencv.js有以下简单文件:

<!DOCTYPE html>
<html>
  <head>
    <script
      async
      src="https://docs.opencv.org/master/opencv.js"
      onload="onOpenCvLoaded();"
      type="text/javascript"
    ></script>
  </head>
  <body>
    <script>
      function onOpenCvLoaded() {
        console.log(cv);
        test(cv);
      }
      function test() {
        console.log(new cv.Mat());
      }
    </script>
  </body>
</html>

我希望在控制台中看到一个新的 Mat 实例,但我得到了:

Uncaught TypeError: cv.Mat is not a constructor
    at test (test.html:18)
    at onOpenCvLoaded (test.html:15)
    at HTMLScriptElement.onload (test.html:9)
test    @   test.html:18
onOpenCvLoaded  @   test.html:15
onload  @   test.html:9

但是new cv.Mat(),如果我直接在控制台中输入,则可以。里面发生了什么,我怎样才能让 new cv.Mat() 在test函数内工作?

标签: javascriptopencv

解决方案


我找到了提供答案的链接:https ://dev.to/kjunichi/requireopencvjs-is-not-enough-for-using-opencvjs-8ff

cv在完全初始化时执行一个函数:

cv['onRuntimeInitialized']=()=>{
          let mat = new cv.Mat();
          console.log(mat.size());
          mat.delete();
};

推荐阅读