<div>Teachable Machine Image Model</div>
<input type="file" id="image-upload" accept="image/*"/>
<div id="image-container"></div>
<div id="label-container"></div>
<script
src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@teachablemachine/image@latest/dist/
teachablemachine-image.min.js"></script>
<script type="text/javascript">
// the link to your model provided by Teachable Machine export panel
const MODEL_URL = "#####link#####";
let model, labelContainer, maxPredictions;
// Load the image model
async function init() {
console.log("Initializing...");
const modelURL = MODEL_URL + "model.json";
const metadataURL = MODEL_URL + "metadata.json";
try {
// load the model and metadata
model = await tmImage.load(modelURL, metadataURL);
maxPredictions = model.getTotalClasses();
console.log("Model loaded successfully");
// append label elements to the DOM
labelContainer = document.getElementById("label-container");
labelContainer.innerHTML = ''; // Clear previous labels
for (let i = 0; i < maxPredictions; i++) {
labelContainer.appendChild(document.createElement("div"));
}
} catch (err) {
console.error("Error during initialization:", err);
}
}
// Handle image upload and prediction
async function predict(event) {
const file = event.target.files[0];
if (!file) {
console.log("No file selected");
return;
}
const imageContainer = document.getElementById("image-container");
imageContainer.innerHTML = ""; // Clear previous images
const img = document.createElement("img");
img.src = URL.createObjectURL(file);
img.width = 200; // Set image display width
img.onload = async () => {
imageContainer.appendChild(img);
console.log("Image loaded, making prediction...");
try {
const prediction = await model.predict(img);
console.log("Prediction result:", prediction); // Logging the
prediction result
for (let i = 0; i < maxPredictions; i++) {
const classPrediction =
prediction[i].className + ": " + (prediction[i].probability
* 100).toFixed(2) + "%";
labelContainer.childNodes[i].innerHTML = classPrediction;
}
} catch (err) {
console.error("Prediction error:", err);
}
};
}
document.getElementById("image-upload").addEventListener("change", predict);
// Initialize the model
init();
</script>