Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lakshmananmurugesan/251439e786e266b761968d461e922375 to your computer and use it in GitHub Desktop.
Save lakshmananmurugesan/251439e786e266b761968d461e922375 to your computer and use it in GitHub Desktop.
Web AI - Simple image classification
<!DOCTYPE html>
<html>
<head>
<title>Web AI with TensorFlow.js</title>
</head>
<body>
<h1>Image Classifier (MobileNet)</h1>
<input type="file" accept="image/*" onchange="loadImage(event)">
<br><br>
<img id="inputImage" width="300"/>
<p id="result">Prediction will appear here</p>
<!-- TensorFlow.js -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<!-- Pretrained MobileNet model -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet"></script>
<script>
let net;
// Load the MobileNet model when the page loads
async function app() {
net = await mobilenet.load(); // Load pre-trained model
document.getElementById('result').innerText = 'Model loaded. Upload an image.';
}
// Handle the image file input and display it
function loadImage(event) {
const image = document.getElementById('inputImage');
image.src = URL.createObjectURL(event.target.files[0]); // Display the selected image
image.onload = () => classifyImage(image); // Classify once image is loaded
}
// Use the model to classify the input image and show the result
async function classifyImage(img) {
const result = await net.classify(img); // Run classification
document.getElementById('result').innerText =
`Prediction: ${result[0].className} \n Probability: ${(result[0].probability * 100).toFixed(2)}%`;
}
// Initialize the app
app();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment