Please bookmark this page to avoid losing your image tool!

Image License Plate Blurring 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,
    blurRadius = 5,
    tesseractLang = 'eng',
    minChars = 3,
    maxChars = 10,
    minAspectRatio = 1.5,
    maxAspectRatio = 6.0,
    confidenceThreshold = 60
) {
    // Helper function to load Tesseract.js and ensure it's ready.
    // It uses a global promise to prevent multiple loading attempts.
    async function _ensureTesseractLoaded() {
        if (typeof window.Tesseract !== 'undefined' && typeof window.Tesseract.recognize === 'function') {
            return window.Tesseract;
        }

        if (!window.tesseractLoadPromise) {
            window.tesseractLoadPromise = new Promise((resolve, reject) => {
                const scriptUrl = 'https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js';
                const script = document.createElement('script');
                script.id = 'tesseract-script'; // Optional: an ID for easier DOM inspection
                script.src = scriptUrl;
                
                script.onload = () => {
                    if (typeof window.Tesseract !== 'undefined' && typeof window.Tesseract.recognize === 'function') {
                        resolve(window.Tesseract);
                    } else {
                        delete window.tesseractLoadPromise; // Allow retry on next call
                        if (document.head.contains(script)) { // Clean up failed script tag
                           try { document.head.removeChild(script); } catch(e) {/*ignore*/}
                        }
                        reject(new Error('Tesseract.js loaded but Tesseract object or Tesseract.recognize function not found.'));
                    }
                };
                
                script.onerror = () => {
                    delete window.tesseractLoadPromise; // Allow retry on next call
                    if (document.head.contains(script)) { // Clean up failed script tag
                        try { document.head.removeChild(script); } catch(e) {/*ignore*/}
                    }
                    reject(new Error('Failed to load Tesseract.js from CDN. Check network, CORS, and Content Security Policy.'));
                };
                
                document.head.appendChild(script);
            });
        }
        return window.tesseractLoadPromise;
    }

    const canvas = document.createElement('canvas');
    
    // Ensure the image is loaded and has dimensions.
    // Browsers might set naturalWidth/Height to 0 for unloaded/broken images.
    // `img.complete` is a good check.
    if (!originalImg.complete || originalImg.naturalWidth === 0 || originalImg.naturalHeight === 0) {
        console.warn("Original image is not fully loaded or has zero dimensions. Trying to use width/height attributes if available, but processing might be incorrect or fail.");
        // We'll use provided width/height if naturalWidth/Height are zero, but this is a fallback.
    }

    canvas.width = originalImg.naturalWidth || originalImg.width;
    canvas.height = originalImg.naturalHeight || originalImg.height;

    if (canvas.width === 0 || canvas.height === 0) {
        console.error("Cannot process image: final canvas dimensions are zero. Ensure the image is loaded and has valid dimensions.");
        return canvas; // Return an empty (zero-sized) canvas
    }

    const ctx = canvas.getContext('2d');
    try {
        ctx.drawImage(originalImg, 0, 0, canvas.width, canvas.height);
    } catch (e) {
        console.error("Error drawing image to canvas. Ensure image is valid and loaded:", e);
        return canvas; // Return canvas, possibly empty or partially drawn
    }


    const effectiveBlurRadius = Math.max(0, blurRadius);

    // If blur radius is 0, no blurring is needed. Tesseract.js processing can be skipped.
    if (effectiveBlurRadius === 0) {
        return canvas;
    }

    let MyTesseract;
    try {
        MyTesseract = await _ensureTesseractLoaded();
    } catch (error) {
        console.error("Failed to load or initialize Tesseract.js:", error);
        // Return the canvas with the original image if Tesseract can't be loaded.
        return canvas;
    }

    try {
        // console.log(`Starting text recognition with Tesseract.js (lang: ${tesseractLang})...`);
        // Use the canvas (which has the image drawn on it) as input for Tesseract.
        const { data: { lines } } = await MyTesseract.recognize(
            canvas,
            tesseractLang,
            {
                // logger: m => console.log(m.status, m.progress) // Uncomment for detailed progress logs
            }
        );
        // console.log(`Tesseract.js recognition complete. Found ${lines.length} lines of text.`);

        for (const line of lines) {
            // Normalize text: remove non-alphanumeric characters and convert to uppercase.
            // This helps in matching typical license plate formats.
            const plateTextCandidate = line.text.replace(/[^a-zA-Z0-9]/g, '').toUpperCase();
            
            const { x0, y0, x1, y1 } = line.bbox;
            const width = x1 - x0;
            const height = y1 - y0;

            // Skip if bounding box dimensions are invalid.
            if (width <= 0 || height <= 0) {
                continue;
            }

            const aspectRatio = width / height;

            // Apply heuristic filters to identify potential license plates.
            const isLikelyPlate =
                plateTextCandidate.length >= minChars &&
                plateTextCandidate.length <= maxChars &&
                aspectRatio >= minAspectRatio &&
                aspectRatio <= maxAspectRatio &&
                line.confidence >= confidenceThreshold;

            if (isLikelyPlate) {
                // console.log(`Applying blur to likely license plate: "${line.text.trim()}" (Normalized: "${plateTextCandidate}") at [${x0},${y0},${width},${height}], Confidence: ${line.confidence.toFixed(2)}%`);
                
                // Apply blur using canvas filter.
                // It's important to draw the segment from the *original image* source,
                // not from the canvas itself, to avoid re-blurring or blurring already modified pixels
                // if multiple detected regions overlap.
                ctx.filter = `blur(${effectiveBlurRadius}px)`;
                ctx.drawImage(
                    originalImg,    // Source image
                    x0, y0,         // Source rectangle (sx, sy)
                    width, height,  // Source rectangle (sWidth, sHeight)
                    x0, y0,         // Destination rectangle (dx, dy)
                    width, height   // Destination rectangle (dWidth, dHeight)
                );
                ctx.filter = 'none'; // Reset filter immediately to avoid affecting other draw operations.
            }
        }
    } catch (error) {
        console.error("Error during Tesseract.js recognition or license plate processing:", error);
        // If an error occurs during processing, the canvas might contain the original image
        // or be partially processed. We return it as is.
    }
    
    // Tesseract.js `recognize` function handles its own worker management (creation/termination).
    // If `Tesseract.createWorker` were used, `await worker.terminate()` would be necessary here.

    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 License Plate Blurring Tool is designed to help users blur license plates in images while utilizing text recognition to identify potential license plate regions. This tool can be particularly useful for privacy protection in media sharing, law enforcement operations, and compliance with regulations regarding the broadcasting or publishing of vehicle registration information. Users can customize the blurriness effect and specify parameters for effective license plate detection, ensuring a balance between maintaining the image’s integrity and protecting sensitive information.

Leave a Reply

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