我正在尝试按照tutorial学习openCv。这是我完整的代码:

<script async src="js/opencv.js" onload="openCvReady()" type="text/javascript"></script>
<video id="video" width="320" height="240"></video>
<canvas id="cvOutput" width="320" height="240"></canvas>
<script>
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
let video = document.getElementById('video');
var streaming = false
var handleSuccess = function(stream) {
  video.srcObject = stream;
  video.play()
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');
  context.drawImage(video, 0, 0, canvas.width, canvas.height);
  streaming = true
};


navigator.mediaDevices.getUserMedia({
    audio: false,
    video: true
  })
  .then(handleSuccess)


function openCvReady() {
  cv['onRuntimeInitialized'] = async () => {
    // pause here until streaming is true
    await sleep(5000);
    let canvasOutput = document.getElementById("cvOutput");
    let src = new cv.Mat(video.height, video.width, cv.CV_8UC4);
    let dst = new cv.Mat(video.height, video.width, cv.CV_8UC1);
    let cap = new cv.VideoCapture(video);

    const FPS = 30;
    function processVideo() {
      try {
          if (!streaming) {
              // clean and stop.
              console.log('Clean and stop')
              src.delete();
              dst.delete();
              return;
          }
          let begin = Date.now();
          // start processing.
          cap.read(src);
          cv.cvtColor(src, dst, cv.COLOR_RGBA2GRAY);
          cv.imshow('canvasOutput', dst); //line 54
          // schedule the next one.
          let delay = 1000/FPS - (Date.now() - begin);
          setTimeout(processVideo, delay);
      } catch (err) {
          //utils.printError(err);
          console.log(err)
      }
    };

    // schedule the first one.
    setTimeout(processVideo, 0);

  };
}
</script>
不幸的是,我收到的这个错误对我来说毫无意义,因为如本教程中所述,我有一个video元素和两个canvas元素。这是第54行 cv.imshow('canvasOutput',dst),对我来说还不错,此外,在执行该行之前,我已经无数次确认该元素已经存在于DOM中:
Error: Please input the valid canvas element or id.
    at Object.Module.imshow (opencv.js:30)
    at processVideo (test.html:54)

最佳答案

该行:

cv.imshow('canvasOutput', dst);
是错误的,因为它使用canvas元素的ID,而不是变量名。
尝试:
cv.imshow('cvOutput', dst);

09-19 01:17