Please bookmark this page to avoid losing your image tool!

Image To Binary Converter With Threshold Methods

(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.
/**
 * Converts an image to a binary (black and white) image using various thresholding methods.
 *
 * @param {HTMLImageElement} originalImg The original image object. Assumes the image is fully loaded.
 * @param {string} [method='otsu'] The thresholding method to use. Can be 'fixed', 'otsu', 'mean', or 'median'.
 * @param {number} [threshold=128] The threshold value (0-255) to use for the 'fixed' method. Ignored by other methods.
 * @returns {HTMLCanvasElement} A canvas element displaying the binary image.
 */
function processImage(originalImg, method = 'otsu', threshold = 128) {
    // 1. Create a canvas and get its context
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d', { willReadFrequently: true });
    
    const width = originalImg.naturalWidth;
    const height = originalImg.naturalHeight;
    canvas.width = width;
    canvas.height = height;

    // 2. Draw the original image onto the canvas
    ctx.drawImage(originalImg, 0, 0, width, height);

    // 3. Get image data and prepare for processing
    const imageData = ctx.getImageData(0, 0, width, height);
    const data = imageData.data;
    const totalPixels = width * height;
    const grayValues = new Uint8ClampedArray(totalPixels);

    // 4. Convert the image to grayscale and store grayscale values
    for (let i = 0; i < data.length; i += 4) {
        const r = data[i];
        const g = data[i + 1];
        const b = data[i + 2];
        // Using the luminosity method for grayscale conversion
        const gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
        grayValues[i / 4] = gray;
    }

    // 5. Calculate the threshold based on the selected method
    let calculatedThreshold;

    switch (method.toLowerCase()) {
        case 'fixed':
            calculatedThreshold = Math.max(0, Math.min(255, threshold));
            break;

        case 'mean': {
            let sum = 0;
            for (let i = 0; i < grayValues.length; i++) {
                sum += grayValues[i];
            }
            calculatedThreshold = Math.round(sum / totalPixels);
            break;
        }

        case 'median': {
            // Note: Sorting can be slow for very large images
            const sortedGray = [...grayValues].sort((a, b) => a - b);
            const mid = Math.floor(totalPixels / 2);
            if (totalPixels % 2 === 0) {
                calculatedThreshold = Math.round((sortedGray[mid - 1] + sortedGray[mid]) / 2);
            } else {
                calculatedThreshold = sortedGray[mid];
            }
            break;
        }
        
        case 'otsu':
        default: {
            // Otsu's method implementation
            const histogram = new Array(256).fill(0);
            for (let i = 0; i < grayValues.length; i++) {
                histogram[grayValues[i]]++;
            }

            let totalSum = 0;
            for (let i = 0; i < 256; i++) {
                totalSum += i * histogram[i];
            }

            let sumB = 0; // Sum of intensities in the background
            let wB = 0;   // Weight of background (pixel count)
            let wF = 0;   // Weight of foreground (pixel count)
            let maxVar = 0;
            let bestThreshold = 0;

            for (let t = 0; t < 256; t++) {
                wB += histogram[t];
                if (wB === 0) continue;

                wF = totalPixels - wB;
                if (wF === 0) break;

                sumB += t * histogram[t];

                const mB = sumB / wB; // Mean of background
                const mF = (totalSum - sumB) / wF; // Mean of foreground

                // Calculate between-class variance
                const variance = wB * wF * (mB - mF) ** 2;

                if (variance > maxVar) {
                    maxVar = variance;
                    bestThreshold = t;
                }
            }
            calculatedThreshold = bestThreshold;
            break;
        }
    }

    // 6. Apply the threshold to create the binary image
    for (let i = 0; i < data.length; i += 4) {
        const gray = grayValues[i / 4];
        const value = gray >= calculatedThreshold ? 255 : 0;
        data[i] = value;     // Red
        data[i + 1] = value; // Green
        data[i + 2] = value; // Blue
        // Alpha (data[i + 3]) is unchanged
    }

    // 7. Put the modified image data back onto the canvas
    ctx.putImageData(imageData, 0, 0);

    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 To Binary Converter with Threshold Methods allows users to convert images into binary (black and white) representations using various thresholding techniques. This tool can be utilized for applications such as preparing images for printing, simplifying graphics for machine learning tasks, or creating high-contrast visuals for artistic effects. Users can choose from methods such as fixed thresholding, Otsu’s method, mean, or median for flexible image processing.

Leave a Reply

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