DeveloperBreeze

Building a Real-Time Object Detection Web App with TensorFlow.js and p5.js

In this tutorial, you’ll learn how to create a web application that performs real-time object detection using your webcam. By combining TensorFlow.js—Google’s library for machine learning in JavaScript—with p5.js for creative coding and drawing, you can build an interactive app that detects objects on the fly.

This guide will walk you through setting up your development environment, loading a pre-trained model, capturing video input, and overlaying detection results on the video feed.


Prerequisites

Before you begin, make sure you have the following installed and set up:

  • A modern web browser that supports webcam access (Chrome, Firefox, or Edge).
  • Basic knowledge of HTML, CSS, and JavaScript.
  • Familiarity with p5.js (optional, but helpful).
  • A code editor (Visual Studio Code, Sublime Text, etc.).

You do not need any backend setup since everything runs in the browser using TensorFlow.js and p5.js.


Step 1: Setting Up Your Project

Create a new folder for your project and add an index.html file. In this file, we’ll include the necessary libraries via CDN:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Real-Time Object Detection</title>
  <style>
    body {
      text-align: center;
      background: #222;
      color: #fff;
      font-family: sans-serif;
    }
    canvas {
      border: 2px solid #fff;
    }
  </style>
</head>
<body>
  <h1>Real-Time Object Detection Web App</h1>
  <!-- p5.js and TensorFlow.js -->
  <script src="https://cdn.jsdelivr.net/npm/p5@1.6.0/lib/p5.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.6.0/dist/tf.min.js"></script>
  <!-- Pre-trained model: COCO-SSD -->
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/coco-ssd"></script>
  <script src="sketch.js"></script>
</body>
</html>

This HTML file loads p5.js, TensorFlow.js, and the COCO-SSD model library. We also reference our custom script file (sketch.js), which will contain our application logic.


Step 2: Capturing Video with p5.js

Create a new file called sketch.js in your project folder. We’ll use p5.js to access the webcam and display the video on a canvas:

let video;
let detector;
let detections = [];

function setup() {
  // Create the canvas to match the video dimensions
  createCanvas(640, 480);
  // Capture video from the webcam
  video = createCapture(VIDEO);
  video.size(640, 480);
  video.hide();

  // Load the pre-trained COCO-SSD model
  cocoSsd.load().then(model => {
    detector = model;
    console.log("Model Loaded!");
    // Begin detecting objects every frame
    detectObjects();
  });
}

function detectObjects() {
  detector.detect(video.elt).then(results => {
    detections = results;
    // Continue detection in a loop
    detectObjects();
  });
}

function draw() {
  // Draw the video
  image(video, 0, 0);

  // Draw detection boxes and labels if available
  if (detections) {
    for (let i = 0; i < detections.length; i++) {
      let object = detections[i];
      stroke(0, 255, 0);
      strokeWeight(2);
      noFill();
      rect(object.bbox[0], object.bbox[1], object.bbox[2], object.bbox[3]);
      noStroke();
      fill(0, 255, 0);
      textSize(16);
      text(object.class, object.bbox[0] + 4, object.bbox[1] + 16);
    }
  }
}

Explanation

  • Setup: The setup function initializes the canvas and video capture. The video is hidden by p5.js’s default element so that we can draw it onto the canvas manually.
  • Model Loading: We load the COCO-SSD model asynchronously. Once the model is ready, we start continuous object detection by calling detectObjects().
  • Detection Loop: The detectObjects function uses the loaded model to analyze the current video frame and stores the detection results. It recursively calls itself so that new frames are analyzed continuously.
  • Drawing: In the draw loop, the video feed is displayed and for each detected object, a rectangle and label are drawn. The bounding box coordinates and object class are provided by the model.

Step 3: Running Your App

  1. Open the Project: Open the index.html file in your browser. You might need to serve the files using a local web server (for example, using the VS Code Live Server extension) because accessing webcam streams from local files can be restricted.
  2. Grant Webcam Permission: The browser will prompt you to allow access to the webcam. Grant permission to start the video feed.
  3. Observe the Detection: As the model processes the video stream, you’ll see bounding boxes and labels appear around detected objects (like people, chairs, and more).

Step 4: Experiment and Extend

Now that you have a basic real-time object detection app, consider extending its functionality:

  • Filtering Detections: Display only specific classes (e.g., only people or vehicles).
  • Custom UI Elements: Use p5.js to add buttons or controls that modify detection settings in real time.
  • Performance Optimization: Experiment with frame rate adjustments or model parameters for faster detection.

Conclusion

Congratulations! You’ve built a real-time object detection web application using TensorFlow.js and p5.js. This project demonstrates how to integrate machine learning models into a browser-based environment and interact with live video feeds. With further experimentation, you can adapt this tutorial to a variety of creative projects, from interactive art installations to practical surveillance tools.


Continue Reading

Discover more amazing content handpicked just for you

Tutorial

How to Stop SSH From Timing Out

sudo systemctl restart sshd

On your local machine, edit or create:

Aug 21, 2025
Read More
Tutorial

How to Translate URLs in React (2025 Guide)

npx create-react-app react-i18n-routing
cd react-i18n-routing

Install necessary dependencies:

May 04, 2025
Read More
Tutorial

Globalization in React (2025 Trends & Best Practices)

const today = new Intl.DateTimeFormat(i18n.language).format(new Date());
new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD'
}).format(4999.99);

// Output: $4,999.99

May 04, 2025
Read More
Tutorial

Implementing Internationalization (i18n) in a Large React Application (2025 Guide)

Use the useTranslation hook:

import React from 'react';
import { useTranslation } from 'react-i18next';

const Home = () => {
  const { t, i18n } = useTranslation();

  const changeLanguage = (lng) => {
    i18n.changeLanguage(lng);
  };

  const today = new Date();
  const price = 199.99;

  return (
    <div className="p-4">
      <h1>{t('welcome')}</h1>

      <div className="mt-4">
        <strong>{t('language')}:</strong>
        <button onClick={() => changeLanguage('en')} className="ml-2">EN</button>
        <button onClick={() => changeLanguage('fr')} className="ml-2">FR</button>
      </div>

      <p>{t('date_example', { date: today })}</p>
      <p>{t('price_example', { price })}</p>
    </div>
  );
};

export default Home;

May 04, 2025
Read More
Tutorial

Building Micro-Frontends with Webpack Module Federation (2025 Guide)

Update src/bootstrap.js:

import('./App');

May 04, 2025
Read More
Tutorial

State Management Beyond Redux: Using Zustand for Scalable React Apps

Zustand presents a compelling alternative to Redux for state management in React applications. Its minimalistic API, ease of use, and performance optimizations make it suitable for a wide range of projects, from simple applications to more complex systems.

By reducing boilerplate and simplifying state management, Zustand allows developers to focus more on building features and less on configuring their state management setup.

May 03, 2025
Read More
Tutorial

Mastering React Rendering Performance with Memoization and Context

For components that perform heavy computations, useMemo can cache the result of a calculation, recomputing it only when its dependencies change.([Content That Scales][5])

import React, { useState, useMemo } from 'react';

function ExpensiveComponent({ data }) {
  const processedData = useMemo(() => {
    // Expensive computation
    return data.map(item => /* processing */ item);
  }, [data]);

  return <div>{/* render processedData */}</div>;
}

May 03, 2025
Read More
Tutorial

✅ How to Disable MySQL Password Validation on Ubuntu 25.04

Query OK, 0 rows affected

Check that the validation system is gone:

May 01, 2025
Read More
Tutorial

How to Move the MySQL Data Directory to a New Location on Ubuntu 25.04

sudo apparmor_parser -r /etc/apparmor.d/usr.sbin.mysqld

If needed, recreate the MySQL socket directory:

May 01, 2025
Read More
Tutorial

How to Install PHP, MySQL, and phpMyAdmin on Ubuntu 25.04 (LAMP Stack Setup Guide)

You can now access phpMyAdmin at http://localhost/phpmyadmin.

If you're using Apache and want to set up a virtual host for your Laravel application:

May 01, 2025
Read More
Tutorial

How to Fix NVIDIA Driver Issues on Ubuntu (Dell Vostro 3521)

sudo chmod +x /usr/bin/prime-run

Now test:

Apr 14, 2025
Read More
Cheatsheet

ShadCN Cheatsheet

  • @testing-library/react
  • vitest or jest
npm install --save-dev @testing-library/react @testing-library/jest-dom

Apr 12, 2025
Read More
Tutorial

Avoiding Memory Leaks in C++ Without Smart Pointers

Some legacy APIs require raw pointers. You can still use get():

void legacyFunction(char* data);

void useLegacyAPI() {
    ScopedArray<char> buffer(new char[512]);
    legacyFunction(buffer.get());
}

Apr 11, 2025
Read More
Tutorial

Deep Copy in C++: How to Avoid Shallow Copy Pitfalls

This causes both a.data and b.data to point to the same memory. When both destructors run, delete is called twice on the same pointer — undefined behavior!

A deep copy duplicates the actual data pointed to, not just the pointer.

Apr 11, 2025
Read More
Tutorial

🛡️ Protect Your Forms Like a Pro: Anti-Spam Techniques That Actually Work

// pseudo-code
if (requestsFromIP > 3 in 60 seconds) {
  block temporarily
}

You can also use middleware like:

Apr 04, 2025
Read More
Tutorial

Build a Custom Rate Limiter in Node.js with Redis

mkdir node-rate-limiter
cd node-rate-limiter
npm init -y
npm install express redis dotenv

Create a .env file:

Apr 04, 2025
Read More
Article

هل سينهي الذكاء الاصطناعي مهنة المبرمج؟ اكتشف الحقيقة!

المبرمج المحترف لا يكتب كودًا فقط، بل يفهم احتياجات المشروع ومتطلبات العميل، ويترجمها إلى حلول تقنية.

الذكاء الاصطناعي يولد حلولًا مبنية على بيانات سابقة، لكنه لا يبدع شيئًا من الصفر خارج ما تعلّمه.

Apr 04, 2025
Read More
Article

6 مهارات غير برمجية لازم تتعلمها كمبرمج مستقل علشان تكسب وتنجح في 2025

دي مهارات أساسية. الكود لوحده مش كفاية. العميل مش بيدور على عبقري، بيدور على حد فاهمه وبيفهمه.

الفرق كبير جدًا!

Mar 29, 2025
Read More
Article

5 أسباب تخلي كل مبرمج عربي يبدأ قناة على يوتيوب في 2025

  • بتفهم الأدوات بشكل أعمق
  • بتتحسن في التواصل
  • بتتعود على تبسيط المفاهيم المعقدة

من خلال قناة قوية:

Mar 29, 2025
Read More
Article

أفكار مشاريع برمجية مربحة للمبرمجين العرب في 2025 (ابدأ بها من اليوم!)

  • قاعدة بيانات للأدوات
  • تصنيفات (نصوص - صور - صوت...)
  • تقييمات ومراجعات من المستخدمين

فرصة ممتازة للتصدر في محركات البحث واستهداف نيتش عالي النمو.

Mar 29, 2025
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!