Please bookmark this page to avoid losing your image tool!

Image Topic Search Identifier Tool

(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.
async function processImage(originalImg, maxPredictions = 5) {
    // Utility function to inject external scripts necessary for image classification
    const loadScript = (src, globalVar) => {
        return new Promise((resolve, reject) => {
            if (window[globalVar]) {
                resolve();
                return;
            }
            const script = document.createElement('script');
            script.src = src;
            script.crossOrigin = 'anonymous';
            script.onload = resolve;
            script.onerror = () => reject(new Error(`Failed to load ${src}`));
            document.head.appendChild(script);
        });
    };

    // Safely parse prediction limit
    const maxPredsNum = parseInt(maxPredictions, 10);
    const limit = (!isNaN(maxPredsNum) && maxPredsNum > 0) ? maxPredsNum : 5;

    // Prepare a temporary canvas to explicitly hold image data correctly 
    const tempCanvas = document.createElement('canvas');
    const tempCtx = tempCanvas.getContext('2d');
    const imgW = originalImg.naturalWidth || originalImg.width || 500;
    const imgH = originalImg.naturalHeight || originalImg.height || 500;
    tempCanvas.width = imgW;
    tempCanvas.height = imgH;
    tempCtx.drawImage(originalImg, 0, 0, imgW, imgH);

    let predictions = [];
    let errorMsg = null;

    try {
        // Dynamically load TensorFlow.js and its MobileNet Image Classification model
        await loadScript('https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.20.0/dist/tf.min.js', 'tf');
        await loadScript('https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet@2.1.0/dist/mobilenet.min.js', 'mobilenet');
        
        // Initialize the model and perform image topic classification
        const model = await window.mobilenet.load();
        predictions = await model.classify(tempCanvas);
    } catch (error) {
        console.error('Image Classification Error:', error);
        errorMsg = 'Error: Cannot classify image (Verify CORS / WebGL availability).';
    }

    const numPreds = errorMsg ? 1 : Math.min(predictions.length, limit);

    // Prepare Layout constants to append topics beneath the image
    const minWidth = 480;
    const finalW = Math.max(imgW, minWidth);
    let drawW = imgW;
    let drawH = imgH;
    
    // Scale image layout proportionally if it is narrower than our text area limit
    if (imgW < minWidth) {
        const scale = minWidth / imgW;
        drawW = minWidth;
        drawH = imgH * scale;
    }

    // Allocate height based on number of predictions
    const textH = 70 + (numPreds * 35);
    const finalH = drawH + textH;
    
    // Prepare the final visible canvas element to be returned
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    canvas.width = finalW;
    canvas.height = finalH;

    // Output Base background for the entire resulting layout
    ctx.fillStyle = '#000000';
    ctx.fillRect(0, 0, finalW, finalH);

    // Draw the image
    ctx.drawImage(tempCanvas, 0, 0, finalW, drawH);

    // Setup Text area backdrop
    const textStartY = drawH;
    ctx.fillStyle = '#1e1e1e';
    ctx.fillRect(0, textStartY, finalW, textH);

    // Setup Text Header
    ctx.fillStyle = '#ffffff';
    ctx.font = 'bold 22px sans-serif';
    ctx.textBaseline = 'top';
    ctx.fillText('Identified Topics:', 20, textStartY + 20);

    ctx.font = '18px sans-serif';

    if (errorMsg) {
        // Output failure states securely
        ctx.fillStyle = '#ff6b6b';
        ctx.fillText(errorMsg, 20, textStartY + 60);
    } else if (predictions.length === 0) {
        // Display when zero topics match
        ctx.fillStyle = '#a8e6cf';
        ctx.fillText('No distinct prominent topics could be recognized.', 20, textStartY + 60);
    } else {
        // Render Identified Topics (Name & Prediction Confidence Level)
        for (let i = 0; i < numPreds; i++) {
            const p = predictions[i];
            const prob = (p.probability * 100).toFixed(2) + '%';
            
            // Reformat identifier classname dynamically (stripping off multi-aliases)
            const topicStrs = (p.className || '').split(',');
            let topicStr = topicStrs[0].trim();
            const finalTopicStr = topicStr.charAt(0).toUpperCase() + topicStr.slice(1);
            
            const itemY = textStartY + 60 + (i * 35);
            
            // Topic Label Layout
            ctx.fillStyle = '#4da6ff';
            ctx.fillText(finalTopicStr, 20, itemY);
            
            // Topic Probability Confidence Layout
            ctx.fillStyle = '#a8e6cf';
            const probWidth = ctx.measureText(prob).width;
            ctx.fillText(prob, finalW - probWidth - 20, itemY);
            
            // Dotted Link Line connecting topic string to its prediction percentage
            ctx.strokeStyle = '#444444';
            ctx.beginPath();
            const startX = 20 + ctx.measureText(finalTopicStr).width + 15;
            const endX = finalW - probWidth - 35;
            if (endX > startX) {
                ctx.setLineDash([3, 4]);
                ctx.moveTo(startX, itemY + 10);
                ctx.lineTo(endX, itemY + 10);
                ctx.stroke();
                ctx.setLineDash([]); // cleanup for subsequent passes
            }
        }
    }

    // Returns a monolithic canvas encompassing both the original image and AI topics overlay
    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

The Image Topic Search Identifier Tool uses artificial intelligence to analyze images and identify the most prominent objects or subjects within them. It provides a list of recognized topics along with a confidence percentage for each prediction. This tool is useful for automatically tagging image libraries, generating descriptive metadata for accessibility, or categorizing visual content for digital organization.

Leave a Reply

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