You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular使用@teachablemachine/image预测报t不是函数错误如何解决

问题根因

该报错由两个核心问题触发:

  • @teachablemachine/image包内置了适配好的TensorFlow.js版本,和项目单独安装的@tensorflow/tfjs版本冲突,导致tfjs内核函数加载异常
  • model.predict()是同步方法,代码中错误添加了await做异步包装,触发运行时异常
修复步骤
  1. 卸载项目单独安装的TensorFlow.js依赖,执行命令:
    npm uninstall @tensorflow/tfjs
  2. 删除代码中单独引入tfjs的语句:import * as tf from '@tensorflow/tfjs';
  3. 修正predict调用方式,去掉多余的await,同时调整setInterval的采样间隔到100ms,避免高频调用导致浏览器阻塞
  4. 可选优化:将预测逻辑放到Angular NgZone外执行,避免zone.js拦截tfjs内部方法导致异常
  5. 依赖修改完成后,删除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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 08:54:03