Please bookmark this page to avoid losing your image tool!

Image Food Product Categorization 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, topK = 3) {
    /**
     * Dynamically loads a script and returns a promise that resolves when the script is loaded.
     * Caches a promise to avoid reloading the same script multiple times.
     * @param {string} src The URL of the script to load.
     * @returns {Promise<void>}
     */
    const loadScript = (() => {
        const loadedScripts = {};
        return (src) => {
            if (!loadedScripts[src]) {
                loadedScripts[src] = new Promise((resolve, reject) => {
                    const script = document.createElement('script');
                    script.src = src;
                    script.onload = () => resolve();
                    script.onerror = () => reject(new Error(`Script load error for ${src}`));
                    document.head.appendChild(script);
                });
            }
            return loadedScripts[src];
        };
    })();

    /**
     * Loads the MobileNet model. Caches the model promise to avoid re-loading.
     */
    const loadModel = (() => {
        let modelPromise = null;
        return async () => {
            if (!modelPromise) {
                modelPromise = new Promise(async (resolve, reject) => {
                    try {
                        // Load TensorFlow.js and the MobileNet model scripts
                        await loadScript('https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.11.0/dist/tf.min.js');
                        await loadScript('https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet@2.1.1/dist/mobilenet.min.js');

                        // Load the model
                        const model = await mobilenet.load();
                        resolve(model);
                    } catch (error) {
                        console.error("Failed to load model:", error);
                        reject(error);
                    }
                });
            }
            return modelPromise;
        };
    })();
    
    // Create the main container for the output
    const resultContainer = document.createElement('div');
    resultContainer.style.fontFamily = 'Arial, sans-serif';
    resultContainer.style.padding = '15px';
    resultContainer.style.backgroundColor = '#f9f9f9';
    resultContainer.style.border = '1px solid #ddd';
    resultContainer.style.borderRadius = '8px';
    resultContainer.style.maxWidth = '400px';

    const loadingText = document.createElement('p');
    loadingText.textContent = 'Loading classification model...';
    loadingText.style.margin = '0';
    resultContainer.appendChild(loadingText);

    try {
        // 1. Load the pre-trained model
        const model = await loadModel();
        loadingText.textContent = 'Analyzing image...';

        // 2. Classify the image
        const predictions = await model.classify(originalImg, topK);

        // 3. Display the results
        resultContainer.innerHTML = ''; // Clear loading text

        const title = document.createElement('h3');
        title.textContent = 'Top Food Categories:';
        title.style.margin = '0 0 10px 0';
        resultContainer.appendChild(title);

        if (predictions && predictions.length > 0) {
            const list = document.createElement('ul');
            list.style.listStyleType = 'none';
            list.style.padding = '0';
            list.style.margin = '0';

            predictions.forEach(prediction => {
                const listItem = document.createElement('li');
                listItem.style.marginBottom = '10px';

                // Format the class name (e.g., "Granny Smith, apple" -> "Granny Smith")
                const className = document.createElement('span');
                const mainClassName = prediction.className.split(',')[0];
                className.textContent = mainClassName.charAt(0).toUpperCase() + mainClassName.slice(1);
                className.style.fontWeight = 'bold';
                className.style.display = 'block';
                className.style.marginBottom = '4px';
                listItem.appendChild(className);

                // Create a progress bar for the confidence score
                const confidenceWrapper = document.createElement('div');
                confidenceWrapper.style.width = '100%';
                confidenceWrapper.style.backgroundColor = '#e0e0e0';
                confidenceWrapper.style.borderRadius = '5px';
                confidenceWrapper.style.overflow = 'hidden';

                const probability = prediction.probability * 100;
                const confidenceBar = document.createElement('div');
                confidenceBar.style.width = `${probability}%`;
                confidenceBar.style.backgroundColor = '#4CAF50';
                confidenceBar.style.height = '20px';
                confidenceBar.style.textAlign = 'right';
                confidenceBar.style.color = 'white';
                confidenceBar.style.fontSize = '12px';
                confidenceBar.style.lineHeight = '20px';
                confidenceBar.style.paddingRight = '5px';
                confidenceBar.style.boxSizing = 'border-box';
                confidenceBar.style.transition = 'width 0.5s ease-in-out';
                confidenceBar.textContent = `${probability.toFixed(1)}%`;

                confidenceWrapper.appendChild(confidenceBar);
                listItem.appendChild(confidenceWrapper);
                list.appendChild(listItem);
            });
            resultContainer.appendChild(list);
        } else {
            const noResultText = document.createElement('p');
            noResultText.textContent = 'Could not classify the image. Please try another one.';
            resultContainer.appendChild(noResultText);
        }

    } catch (error) {
        console.error("Error during image classification:", error);
        resultContainer.innerHTML = ''; // Clear any previous content
        const errorText = document.createElement('p');
        errorText.textContent = 'An error occurred. Please check the console for details.';
        errorText.style.color = 'red';
        resultContainer.appendChild(errorText);
    }

    return resultContainer;
}

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 Food Product Categorization Tool allows users to upload images of food products and receive classifications indicating the primary categories of the items depicted in the images. Utilizing a pre-trained model, the tool analyzes the uploaded image and provides insights into its content, displaying the most likely food categories along with confidence scores. This tool is especially useful for businesses in food retail, marketing analysis, and inventory management, as it helps in identifying products and enhancing customer engagement through better categorization.

Leave a Reply

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