Struggling with an error while experimenting with tensorflow/teachable machine on vuejs

After experimenting with vuejs and , I encountered an issue while trying to export the model for my project. As I adjusted the syntax to fit Vue, I hit a roadblock when the code returned an error stating "cannot read properties of undefined...."

console.log(this.webcam.canvas); // returns <canvas width="200" height="200"></canvas>
const prediction = await this.model.predict(this.webcam.canvas);

https://i.sstatic.net/ITlr4.png

<template>
    <Head title="Camera"/>
    <div class="min-h-screen bg-white pt-12">
        <div class="flex flex-col justify-center items-center">
            <div>Teachable Machine Image Model</div>
            <button class="bg-blue-400 p-2 rounded" type='button' @click='init'>Start</button>

            <div id='webcam-container'></div> CAMERA
            <div id='label-container'></div> NONE
        </div>
    </div>
</template>


<script>
import { Head } from '@inertiajs/inertia-vue3';
import * as tf from '@tensorflow/tfjs';
import * as tmImage from '@teachablemachine/image';

export default {
    components: {
        Head,
    },
    props: {
        products: {
            type: Object,
            default: {}
        },
    },
    data() {
        return {
            model: null,
            webcam: null,
            labelContainer: null,
            maxPredictions: null,
            isIos: false,
            image: null,
        }
    },
    mounted () {
        // this.init();
    },
    methods: {
    // Load the image model and setup the webcam
        async init() {
            const URL = 'https://teachablemachine.withgoogle.com/models/xxxxxxx/';

            const modelURL = URL + "model.json";
            const metadataURL = URL + "metadata.json";

            // load the model and metadata
            // Refer to tmImage.loadFromFiles() in the API to support files from a file picker
            // or files from your local hard drive
            // Note: the pose library adds "tmImage" object to your window (window.tmImage)
            this.model = await tmImage.load(modelURL, metadataURL);
            this.maxPredictions = this.model.getTotalClasses();

            // Convenience function to setup a webcam
            const flip = true; // whether to flip the webcam
            this.webcam = new tmImage.Webcam(200, 200, flip); // width, height, flip
            await this.webcam.setup(); // request access to the webcam
            await this.webcam.play();
            window.requestAnimationFrame(this.loop);

            // append elements to the DOM
            document.getElementById("webcam-container").appendChild(this.webcam.canvas);
            this.labelContainer = document.getElementById("label-container");
            for (let i = 0; i < this.maxPredictions; i++) { // and class labels
                this.labelContainer.appendChild(document.createElement("div"));
            }
        },
        async loop() {
            this.webcam.update(); // update the webcam frame
            await this.predict();
            window.requestAnimationFrame(this.loop);
        },
        async predict() { // run the webcam image through the image model
            // predict can take in an image, video or canvas html element
            console.log(this.webcam.canvas);
            const prediction = await this.model.predict(this.webcam.canvas);
            for (let i = 0; i < this.maxPredictions; i++) {
                const classPrediction =
                    prediction[i].className + ": " + prediction[i].probability.toFixed(2);
                this.labelContainer.childNodes[i].innerHTML = classPrediction;
            }
        },
    },
}
</script>

Answer №1

Modify the following code snippet

this.model = await tmImage.load(modelURL, metadataURL);

to achieve this new implementation

this.model = Object.freeze(await tmImage.load(modelURL, metadataURL));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

'this' while being utilized in a nested function

const EventEmitter = require('events').EventEmitter; const Counter = function (init) { this.increment = function () { init++; this.emit('incremented', init); } } ...

Reset functionality for input selector is malfunctioning

My HTML code looks like this: <input type="number"> <br> <input type="number"> <br> <input type="number"> <br> <button>+</button> In my JS script, I have the following: $('input').on('c ...

Ways to activate an event with select2

Hey there! I have a unique setup on my selling item page with select tags. The first select tag is created using HTML, while the others are dynamically added using jQuery when the user clicks on an "Add More" button. <select id='code0' onclic ...

Monitor the latest website address being typed into the browser

Is it possible to track the new URL entered by a user in the browser when they leave the current page using the onunload event? For example, if a user is currently on www.xyz.com/page1.aspx and then types a new URL into the browser, I want to capture that ...

When accessing the JavaScript date object, no output is being returned

I have a calendar layout consisting of floated div elements, rather than using an actual <table>. My goal is to allow the user to click anywhere on a row to add a new booking. The challenge lies in accurately calculating the time at which they clicke ...

Reassemble the separated string while skipping over every other element in the array created by splitting it

Currently, I am working on the following URL: demo.example.in/posts/0ewsd/13213 My goal is to extract the hostname (demo.example.in) and the path (posts/0ewsd/13213) from this URL. urlHost = 'demo.example.in/posts/0ewsd/13213'; let urlHostName ...

Vue not displaying local images

I'm having trouble creating an image gallery with Vue.js because local images are not loading. I have the src attributes set in the data attribute and can only load images from external sources. For example: data() { return { imag ...

Tips to retrieve an Angular `value` from outside the module

customConfig.js angular.module("steam") .value("customConfig", { baseurl: "http://dev-back1.techgrind.asia/" }); To access the value outside the module, replace the " .." with customConfig.baseurl apiTest.js var frisby = require("frisby"); fris ...

Retrieve the decimal separator and other locale details from the $locale service

After reviewing the angular $locale documentation, I noticed that it only provides an id (in the form of languageId-countryId). It would be helpful to have access to more specific information such as the decimal separator character. Is there a way to retri ...

In the Node environment, why does null evaluate as less than 3 while also being greater than 3?

How come null is false when compared to 3 in node, and true when compared to 3? $ node > null > 3 false > null < 3 true ...

What is the best way to emphasize an element on a webpage with Selenium and Python?

Recently, I inherited an existing selenium framework that utilizes Python for scripting. In order to aid in debugging and other tasks, I am interested in implementing a feature that highlights the element currently being acted upon (such as an input box, l ...

jQuery - Enhancing User Experience with Dynamic Screen Updates

Is there a way to update the screen height when resizing or zooming the screen? Whenever I zoom the screen, the arrows break. I'm also curious if the method I'm using to display images on the screen is effective. It's supposed to be a paral ...

The method window.getComputedStyle retrieves the CSS max-height property containing an unresolved calc() function

Has anyone encountered a challenge with a function related to Angular in their project? Here is a snippet of the code causing issues: console.log(window.getComputedStyle(this.frontLayer.nativeElement).maxHeight); And within the component template: <di ...

Utilizing jQuery to remove a class with an Ajax request

My setup includes two cards, one for entering a postcode and another with radio buttons to select student status (initially hidden). An Ajax request validates the postcode input - turning the card green if valid (card--success) and revealing the student se ...

Choose to either check or uncheck boxes using ReactJS

After successfully creating a function to select either single or multiple boxes, I encountered an issue with the "Select all" feature. Any suggestions on how to resolve this? (I'm utilizing the material-ui library for my checkboxes, which are essenti ...

After utilizing a while loop with class objects, make sure to reset them afterwards

I am facing a dilemma due to Js referencing objects. Within my Js "class," I have created a new player with various variables, strings, arrays, and functions to check specific conditions related to those variables. As part of my code, I am running a whil ...

Verifying the functionality of a custom directive in Angular 2 (Ionic 2) through unit

In my ionic application, I developed a custom directive specifically for text masking, aimed at formatting phone numbers within input fields. The core functionality of this directive revolves around utilizing ngControl to facilitate the retrieval and assig ...

Creating a dynamic hyperlink variable that updates based on user input

I am attempting to create a dynamic mailto: link that changes based on user input from a text field and button click. I have successfully achieved this without using the href attribute, but I am encountering issues when trying to set it with the href attr ...

Interactive Communication: PHP and JQuery Messaging Platform

I am developing a social networking platform and I am looking to integrate a chat feature. Currently, I have a home.php page that displays a list of friends. The friends list is loaded dynamically using jQuery and PHP, like this: function LoadList() { ...

Create a feature that allows users to search as they navigate the map using Leaflet

Exploring the idea of incorporating a dynamic "Search as I move the map" feature similar to Airbnb using Leaflet. Striving to strike a balance between loading data relevant to the displayed portion of the map and minimizing unnecessary API requests trigger ...