Please bookmark this page to avoid losing your image tool!

Image Detector

(Free & Supports Bulk Upload)

Drag & drop your images here or

The result will appear here...
You can edit the below JavaScript code to customize the image tool.
/**
 * This function acts as an "Image Detector" by identifying common objects within an image.
 * It uses the pre-trained COCO-SSD model from TensorFlow.js.
 * The function will draw the original image on a canvas and then overlay bounding boxes
 * and labels on any objects it detects with a sufficient confidence score.
 *
 * It dynamically loads the necessary machine learning model and libraries from a CDN,
 * and caches them to improve performance on subsequent calls.
 *
 * @param {HTMLImageElement} originalImg The original image object to process.
 * @param {number} [scoreThreshold=0.5] The minimum confidence score (0-1) for a detection to be displayed.
 * @param {string} [boxColor='#00FF00'] The color of the bounding box and label background, in CSS format (e.g., 'red', '#00FF00').
 * @param {string} [font='16px sans-serif'] The CSS font string for the labels.
 * @returns {Promise<HTMLCanvasElement>} A promise that resolves to a canvas element with the detected objects highlighted.
 */
async function processImage(originalImg, scoreThreshold = 0.5, boxColor = '#00FF00', font = '16px sans-serif') {

    // --- Caching and Script Loading ---
    // Attach loader and model promise to the function object itself to persist across runs.
    if (!processImage.scriptLoader) {
        const scriptCache = {};
        processImage.scriptLoader = (src) => {
            if (!scriptCache[src]) {
                scriptCache[src] = new Promise((resolve, reject) => {
                    const script = document.createElement('script');
                    script.src = src;
                    script.crossOrigin = 'anonymous';
                    script.onload = () => resolve();
                    script.onerror = () => reject(new Error(`Script load error for ${src}`));
                    document.head.appendChild(script);
                });
            }
            return scriptCache[src];
        };
    }

    // --- Canvas Setup ---
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    canvas.width = originalImg.naturalWidth;
    canvas.height = originalImg.naturalHeight;
    ctx.drawImage(originalImg, 0, 0);

    // --- Main Detection Logic ---
    try {
        // Step 1: Load the required scripts for TensorFlow.js and the COCO-SSD model.
        await processImage.scriptLoader('https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest');
        await processImage.scriptLoader('https://cdn.jsdelivr.net/npm/@tensorflow-models/coco-ssd@latest');

        // Step 2: Load the COCO-SSD model. Cache the model promise to avoid reloading.
        if (!processImage.modelPromise) {
            console.log("Loading COCO-SSD model...");
            processImage.modelPromise = cocoSsd.load();
        }
        const model = await processImage.modelPromise;
        console.log("Model loaded successfully.");

        // Step 3: Run detection on the image.
        const predictions = await model.detect(originalImg);
        
        // Step 4: Draw the predictions on the canvas.
        predictions.forEach(prediction => {
            if (prediction.score > scoreThreshold) {
                // Bounding box
                const [x, y, width, height] = prediction.bbox;
                ctx.strokeStyle = boxColor;
                ctx.lineWidth = Math.max(2, Math.round(canvas.width / 350));
                ctx.strokeRect(x, y, width, height);

                // Label
                const text = `${prediction.class} (${Math.round(prediction.score * 100)}%)`;
                ctx.font = font;
                ctx.textBaseline = 'top';

                const textMetrics = ctx.measureText(text);
                const textHeight = textMetrics.actualBoundingBoxAscent + textMetrics.actualBoundingBoxDescent;
                const padding = 5;

                // Label background
                ctx.fillStyle = boxColor;
                ctx.fillRect(x, y, textMetrics.width + padding * 2, textHeight + padding * 2);

                // Label text
                ctx.fillStyle = '#ffffff'; // White text for better contrast on colored background
                ctx.fillText(text, x + padding, y + padding);
            }
        });

    } catch (error) {
        console.error("Error during object detection:", error);
        // Display an error message on the canvas if something goes wrong.
        ctx.fillStyle = 'rgba(255, 0, 0, 0.7)';
        ctx.font = '20px sans-serif';
        ctx.textAlign = 'center';
        ctx.fillText('Object detection failed.', canvas.width / 2, canvas.height / 2);
    }

    return canvas;
}

Free Image Tool Creator

Can't find the image tool you're looking for?
Create one based on your own needs now!

Description

Image Detector is a web-based tool that utilizes machine learning to identify and highlight common objects within an uploaded image. By leveraging the COCO-SSD model, the tool scans the image and draws bounding boxes around detected objects, providing labels with confidence scores. This can be useful for various applications such as analyzing images for educational purposes, creating interactive content, enhancing image accessibility, and integrating image recognition features into web applications.

Leave a Reply

Your email address will not be published. Required fields are marked *