/web-to-ai-ml-integrations

Webcam Capture to ML Model with JavaScript

Learn to capture webcam streams and integrate ML models using JavaScript with our easy, step-by-step guide for innovative web apps!

Book a free  consultation
4.9
Clutch rating 🌟
600+
Happy partners
17+
Countries served
190+
Team members
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

Webcam Capture to ML Model with JavaScript

 Accessing the Webcam Feed 

 
  • navigator.mediaDevices.getUserMedia is the built‐in API for accessing the webcam in modern browsers.
  • This API returns a promise that resolves with a MediaStream object if the user grants permission.

// Select video element from your HTML
const videoElement = document.getElementById('webcam');

// Request access to the webcam
navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => {
// Set the source of the video element to the webcam stream
videoElement.srcObject = stream;
videoElement.play();
})
.catch(error => {
// Handle error in case the user denies webcam access
console.error('Error accessing webcam:', error);
});

 Capturing Frames from the Video Stream 

 
  • The canvas element is used to capture a frame from the video feed.
  • You can draw the current video frame on the canvas, then extract it as an image data object.

// Create a canvas element in your HTML or dynamically via JavaScript
const canvasElement = document.getElementById('captureCanvas');
const canvasContext = canvasElement.getContext('2d');

// Function to capture the current frame from the video
function captureFrame() {
// Draw the video frame on the canvas; width and height should match your video or canvas size
canvasContext.drawImage(videoElement, 0, 0, canvasElement.width, canvasElement.height);
// Get image data from the canvas
const imageData = canvasContext.getImageData(0, 0, canvasElement.width, canvasElement.height);
return imageData;
}

 Integrating a Machine Learning Model with TensorFlow.js 

 
  • TensorFlow.js is a JavaScript library for training and deploying ML models in the browser.
  • You can either load a pre-trained model or define your own model architecture.

// Load a pre-trained model hosted online or locally.
// For example, replace 'model.json' with the path or URL to your model.
async function loadModel() {
  const model = await tf.loadLayersModel('model.json');
  return model;
}

// Load the model at startup
let mlModel;
loadModel().then(loadedModel => {
mlModel = loadedModel;
console.log('ML model loaded successfully');
});

 Preprocessing the Captured Image for the Model 

 
  • ML models usually require image data to be formatted as a tensor in a specific shape and normalized.
  • Preprocess steps can include resizing, scaling pixel values, and optionally converting to grayscale if needed.

// Example function to preprocess image data from canvas for model prediction
function preprocessImage(imageData) {
  // Convert the image data into a tensor
  let tensor = tf.browser.fromPixels(imageData);
  

// Resize the image to the required input shape of the model, for instance 224x224 pixels
tensor = tf.image.resizeBilinear(tensor, [224, 224]);

// Normalize the image values from [0, 255] to [0, 1]
tensor = tensor.toFloat().div(tf.scalar(255));

// Expand dimensions to match the model input if necessary (e.g., [1, 224, 224, 3])
tensor = tensor.expandDims();

return tensor;
}

 Running Inference on the Captured Image 

 
  • Once the image is preprocessed, pass it to the ML model for prediction.
  • Predictions can be classification labels, bounding boxes, or any other type of output defined by your model.

async function predictFrame() {
  // Capture the current frame from the video
  const imageData = captureFrame();
  

// Preprocess the captured image data
const inputTensor = preprocessImage(imageData);

// Obtain predictions from the ML model
const predictions = await mlModel.predict(inputTensor);

// Process the output predictions (e.g., convert logits to probabilities or extract labels)
console.log('Predictions:', predictions);

// Dispose tensor to free memory
inputTensor.dispose();
}

 Integrating Continuous Capture and Prediction 

 
  • Use the browser's requestAnimationFrame function to repeatedly capture frames and predict in a loop.
  • This method ensures that frame processing is timed with the display refresh rate for efficient performance.

function processVideoStream() {
  // Continuously capture frames and run prediction
  predictFrame();
  

// Use requestAnimationFrame for a smooth loop execution
requestAnimationFrame(processVideoStream);
}

// Start the continuous prediction loop after the model has loaded
loadModel().then(() => {
processVideoStream();
});

 Displaying Results on the Web Page 

 
  • Create a simple HTML element (like a div or span) to show the predictions or results.
  • Update this element dynamically after each prediction to provide real-time feedback.

// Assume you have an element in your HTML with the ID 'resultDisplay'
const resultDisplay = document.getElementById('resultDisplay');

async function predictFrameAndDisplay() {
const imageData = captureFrame();
const inputTensor = preprocessImage(imageData);
const predictions = await mlModel.predict(inputTensor);

// Format the predictions for display
// Here, you might convert a tensor to an array, find the highest probability, etc.
predictions.array().then(predictionArray => {
resultDisplay.innerText = 'Predictions: ' + JSON.stringify(predictionArray);
});

inputTensor.dispose();
requestAnimationFrame(predictFrameAndDisplay);
}

// Begin the loop once the model is loaded
loadModel().then(() => {
predictFrameAndDisplay();
});

 Handling Performance and Memory Considerations 

 
  • Dispose of any unused tensors using tensor.dispose() to prevent memory leaks.
  • If the model prediction is heavy, consider throttling the frame rate or running the model on a separate Web Worker.
  • Optimize canvas size and model input dimensions for a balance between performance and accuracy.


Recognized by the best

Trusted by 600+ businesses globally

From startups to enterprises and everything in between, see for yourself our incredible impact.

RapidDev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with.

They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

Arkady
CPO, Praction
Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost.

He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Donald Muir
Co-Founder, Arc
RapidDev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space.

They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Mat Westergreen-Thorne
Co-CEO, Grantify
RapidDev is an excellent developer for custom-code solutions.

We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Emmanuel Brown
Co-Founder, Church Real Estate Marketplace
Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 

This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Samantha Fekete
Production Manager, Media Production Company
The pSEO strategy executed by RapidDev is clearly driving meaningful results.

Working with RapidDev has delivered measurable, year-over-year growth. Comparing the same period, clicks increased by 129%, impressions grew by 196%, and average position improved by 14.6%. Most importantly, qualified contact form submissions rose 350%, excluding spam.

Appreciation as well to Matt Graham for championing the collaboration!

Michael W. Hammond
Principal Owner, OCD Tech

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.