Angular使用@teachablemachine/image预测报t不是函数错误如何解决
问题根因
该报错由两个核心问题触发:
@teachablemachine/image包内置了适配好的TensorFlow.js版本,和项目单独安装的@tensorflow/tfjs版本冲突,导致tfjs内核函数加载异常model.predict()是同步方法,代码中错误添加了await做异步包装,触发运行时异常
修复步骤
- 卸载项目单独安装的TensorFlow.js依赖,执行命令:
npm uninstall @tensorflow/tfjs - 删除代码中单独引入tfjs的语句:
import * as tf from '@tensorflow/tfjs'; - 修正predict调用方式,去掉多余的
await,同时调整setInterval的采样间隔到100ms,避免高频调用导致浏览器阻塞 - 可选优化:将预测逻辑放到Angular NgZone外执行,避免zone.js拦截tfjs内部方法导致异常
- 依赖修改完成后,删除node_modules文件夹和package-lock.json文件,重新执行
npm install,再启动项目避免旧缓存影响
修改后完整代码
import * as tmImage from '@teachablemachine/image'; import { NgZone, Renderer2, ElementRef, ViewChild } from '@angular/core'; interface Prediction { className: string; probability: number; } export class AppComponent { @ViewChild('video') video: ElementRef; model: any; webcam: any; labelContainer: any; maxPredictions: any; predictions: Prediction[]; constructor(private renderer: Renderer2, private ngZone: NgZone) {} async init() { const modelURL = "../assets/tm-my-image-model/model.json"; const metadataURL = "../assets/tm-my-image-model/metadata.json"; // 加载模型和元数据 this.model = await tmImage.load(modelURL, metadataURL); this.maxPredictions = this.model.getTotalClasses(); // 初始化摄像头 const flip = true; this.webcam = new tmImage.Webcam(200, 200, flip); await this.webcam.setup(); await this.webcam.play(); await this.webcam.renderCameraToCanvas(); // 定时采样预测 setInterval(() => { this.webcam.renderCameraToCanvas(); // 预测逻辑放到NgZone外,避免zone干扰tfjs运行 this.ngZone.runOutsideAngular(() => { const prediction = this.model.predict(this.webcam.canvas); // 需要更新视图时再放回NgZone内执行 this.ngZone.run(() => { this.predictions = prediction; }); }); }, 100); this.renderer.appendChild(this.video.nativeElement, this.webcam.canvas); } }
内容的提问来源于stack exchange,提问作者Dhiraj Baruah
相关产品推荐
相关产品推荐

