Tensorflow.js tf.browser.fromPixels() 必须是 HTMLVideoElement

Tensorflow.js tf.browser.fromPixels() must be an HTMLVideoElement

我在 node + nwjs 项目中使用 tensorflow.js,当我将视频元素作为 tensowflow fromPixels 方法的输入时,我在控制台输出了这个奇怪的错误:

Uncaught (in promise) Error: pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was HTMLVideoElement

所以我不明白哪里出了问题...

产生错误的这行代码是:

const input_tensor = tf.browser.fromPixels(video);

video定义为:

export const video = document.getElementById("webcam");

指的是这个HTML元素:

<video id="webcam" autoplay muted></video>

视频元素尚未加载以显示视频。只有在视频开始加载

后,才应执行以下 fromPixel
const videoElement = document.getElementById("webcam");

videoElement.addEventListener('loadeddata', (e) => {
   //Video should now be loaded but we can add a second check

   if(videoElement.readyState >= 3){
       const input_tensor = tf.browser.fromPixels(video);
   }

});