Please bookmark this page to avoid losing your image tool!

Image Sobel Edge Detection Overlay

(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.
/**
 * Applies a Sobel edge detection filter to an image and overlays the detected edges
 * on top of the original image.
 *
 * @param {HTMLImageElement} originalImg The original image object.
 * @param {number} [threshold=100] The brightness threshold to determine if a pixel is an edge. Values range from 0 to 255.
 * @param {string} [edgeColor='#00FF00'] The color of the detected edges (e.g., '#FF0000', 'rgb(0,255,0)', 'green').
 * @returns {HTMLCanvasElement} A new canvas element with the Sobel edges overlaid on the original image.
 */
function processImage(originalImg, threshold = 100, edgeColor = '#00FF00') {
    const width = originalImg.width;
    const height = originalImg.height;

    // 1. Create a canvas and draw the original image onto it.
    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    const ctx = canvas.getContext('2d', { willReadFrequently: true });
    ctx.drawImage(originalImg, 0, 0);

    // 2. Get the image data and create a grayscale version.
    const imageData = ctx.getImageData(0, 0, width, height);
    const data = imageData.data;
    const grayscaleData = new Uint8ClampedArray(width * height);

    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 = 0.299 * r + 0.587 * g + 0.114 * b;
        grayscaleData[i / 4] = gray;
    }

    // 3. Prepare for Sobel operator.
    const edgeImageData = ctx.createImageData(width, height);
    const edgeData = edgeImageData.data;

    // Helper to get grayscale pixel value, handling borders.
    const getGray = (x, y) => {
        if (x < 0 || x >= width || y < 0 || y >= height) return 0;
        return grayscaleData[y * width + x];
    };

    // Sobel kernels for horizontal and vertical edge detection.
    const kernelX = [
        [-1, 0, 1],
        [-2, 0, 2],
        [-1, 0, 1]
    ];
    const kernelY = [
        [-1, -2, -1],
         [0,  0,  0],
         [1,  2,  1]
    ];
    
    // Parse the edgeColor string to get RGB values.
    // This trick uses the browser's own parser.
    const tempElem = document.createElement('div');
    tempElem.style.color = edgeColor;
    // The element must be in the DOM for getComputedStyle to work.
    document.body.appendChild(tempElem);
    const computedColor = window.getComputedStyle(tempElem).color;
    document.body.removeChild(tempElem);
    
    const rgb = computedColor.match(/\d+/g).map(Number);
    const [rEdge, gEdge, bEdge] = rgb;

    // 4. Apply the Sobel operator to each pixel.
    for (let y = 1; y < height - 1; y++) {
        for (let x = 1; x < width - 1; x++) {
            let pixelX = 0;
            let pixelY = 0;

            // Apply 3x3 kernels
            for (let j = -1; j <= 1; j++) {
                for (let i = -1; i <= 1; i++) {
                    const gray = getGray(x + i, y + j);
                    pixelX += gray * kernelX[j + 1][i + 1];
                    pixelY += gray * kernelY[j + 1][i + 1];
                }
            }

            // Calculate gradient magnitude.
            const magnitude = Math.sqrt(pixelX * pixelX + pixelY * pixelY);

            // If magnitude is above the threshold, color it as an edge.
            if (magnitude > threshold) {
                const index = (y * width + x) * 4;
                edgeData[index] = rEdge;     // R
                edgeData[index + 1] = gEdge; // G
                edgeData[index + 2] = bEdge; // B
                edgeData[index + 3] = 255;   // A (fully opaque)
            }
        }
    }

    // 5. Draw the detected edges on top of the original image.
    // We create a temporary canvas for the edge data, because drawImage
    // respects transparency, which is exactly what we need for an overlay.
    const edgeCanvas = document.createElement('canvas');
    edgeCanvas.width = width;
    edgeCanvas.height = height;
    const edgeCtx = edgeCanvas.getContext('2d');
    edgeCtx.putImageData(edgeImageData, 0, 0);

    // Draw the transparent canvas containing only edges onto the main canvas.
    ctx.drawImage(edgeCanvas, 0, 0);

    // 6. Return the final composed canvas element.
    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 Sobel Edge Detection Overlay tool applies a Sobel edge detection filter to images, highlighting the edges on top of the original image. This tool is useful for various applications such as enhancing images for computer vision tasks, creating artistic effects, or preparing images for further image processing. Users can customize the brightness threshold for edge detection and choose the color of the detected edges, making it versatile for different visual requirements.

Leave a Reply

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