【问题标题】:Tensorflow.js prediction result doesn't changeTensorflow.js 预测结果不变
【发布时间】:2020-09-16 19:35:10
【问题描述】:

我使用 Google Teachable Machines (Image) 训练了我的模型,并将该模型包含在我的 Ionic Angular 应用程序中。我成功加载了模型并使用相机预览来预测相机图像中显示的类。 画布中显示的图片会正确更改,但 predict() 方法每次调用都会返回相同的结果。

import * as tmImage from '@teachablemachine/image';
...

async startPrediction() {
   this.model = await tmImage.load(this.modelURL, this.metadataURL);
   this.maxPredictions = this.model.getTotalClasses();
   console.log('classes: ' + this.maxPredictions); //works properly

   requestAnimationFrame(() => {
     this.loop();
   });
}


async loop() {
   const imageAsBase64 = await this.cameraPreview.takeSnapshot({ quality: 60 });
   const canvas = document.getElementById('output') as HTMLImageElement;
   //image changes properly, I checked it with a canvas output
   canvas.src = 'data:image/jpeg;base64,' + imageAsBase64; 

   const prediction = await this.model.predict(canvas);
   for (let i = 0; i < this.maxPredictions; i++) {
     const classPrediction =
       prediction[i].className + ': ' + prediction[i].probability.toFixed(2);
      //probability doesn't change, even if I hold the camera close over a trained image
   }

   requestAnimationFrame(() => {
      this.loop();
   });
}

预测结果例如:class1 = 0.34, class2 = 0.66 但不会改变。 我希望你能帮助我找到我的错误,提前谢谢!

【问题讨论】:

    标签: angularjs tensorflow ionic-framework tensorflow.js


    【解决方案1】:

    在您调用预测模型之前,图像可能尚未加载。已经讨论过herethere

    function load(url){
      return new Promise((resolve, reject) => {
         canvas.src = url
         canvas.onload = () => {
              resolve(canvas)
            }   
       })
    }
    
    await load(base64Data)
    // then the image can be used for prediction
    

    【讨论】:

    • 非常感谢,这是有道理的,但似乎从未调用过 onload(),对此有什么想法吗?
    • 图片加载完成后在后台调用
    • 但它没有被调用,我需要在我的 html 中添加一个元素吗?
    • 您使用了await 吗?因为await 会等到承诺的解决。如果 promise 被解决,这意味着 onload 被调用了
    • src需要在onload函数之后设置。我编辑了答案
    猜你喜欢
    • 1970-01-01
    • 2019-07-19
    • 2018-11-29
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多