Quagga2 Documentation

repository·master·Indexed 21 days ago

https://github.com/ericblade/quagga2

An advanced JavaScript barcode scanner library for real-time localization and decoding of various barcode types (including EAN, Code 128, and Code 39) using camera streams via getUserMedia or static images. It features a two-stage process of locating barcodes via a binary image and skeletonization, then decoding the encoded information. The library supports browser-based live streams and Node.js file-based decoding, providing a comprehensive API for camera management, event handling, and custom reader registration.

Tokens
46.5K
Snippets
140
Records
195
Agent score
75%

What's inside Quagga2

  1. What is Quagga2?

    master

    Quagga2 is a JavaScript library designed for decoding common barcodes (such as Code128 and EAN13) directly in the browser. It supports various image sources, including:

    • Single images: Provided via file-input.
    • Real-time streams: Preferred method using a camera stream via getUserMedia for continuous decoding.
  2. Access Quagga2 API and Configuration Reference

    master

    For precise technical details, use the following reference areas:

    • API Documentation: Use this for complete reference of all Quagga2 methods, callbacks, and events.
    • Configuration Options: Use this for detailed documentation of every configuration parameter and its effects.
    • Camera Access API: Use this for methods controlling camera access, torch/flash, and device enumeration.
    • Supported Barcode Types: Use this to see the list of all supported barcode formats, their characteristics, and use cases.
    • Browser Support: Use this to check the browser compatibility matrix and required Web APIs.
    • Dependencies: Use this to understand which package dependencies are bundled versus dev-only.
  3. Compare Cypress and Playwright Directory Structures

    master

    When migrating, the project structure changes from a Cypress-centric layout to a Playwright-centric layout.

    Cypress Structure:

    • Tests located in cypress/e2e/ with .cy.ts extension.
    • Config in cypress.config.ts.

    Playwright Structure:

    • Tests located in tests/e2e/ with .spec.ts extension.
    • Config in playwright.config.ts.
    • Fixtures located in tests/fixtures/.
  4. Access and use Quagga canvas elements

    master

    Quagga manages two canvas elements for visualization: Quagga.canvas.dom.image (the processed grayscale image) and Quagga.canvas.dom.overlay (a transparent layer for drawing).

    Overlay Canvas

    • Purpose: Drawing bounding boxes, scan lines, and visual feedback.
    • Coordinates: Coordinates from result.box and result.boxes match the overlay canvas directly; no scaling is required when drawing on the overlay.
    • Availability: Can be disabled via canvas.createOverlay: false.

    Image Canvas

    • Purpose: Contains processed grayscale data; primarily for debugging locator issues.

    Scaling Coordinates for External Canvases

    If you need to draw on a different canvas (like the original video element), you must scale the coordinates manually:

    const scaleX = video.videoWidth / Quagga.canvas.dom.image.width;
    const scaleY = video.videoHeight / Quagga.canvas.dom.image.height;
    const scaledBox = result.box.map(p => [p[0] * scaleX, p[1] * scaleY]);
  5. How the Quagga2 processing pipeline works

    master

    Quagga2 processes images through a sequential multi-stage pipeline to transform raw input into a decoded barcode result. The pipeline follows this flow:

    Input Image $\rightarrow$ Preprocessing $\rightarrow$ Localization $\rightarrow$ Decoding $\rightarrow$ Result

    1. Preprocessing

    Prepares the raw image for analysis by performing:

    • Scaling: Resizing the image based on the inputStream.size configuration.
    • Grayscale conversion: Converting color images to grayscale.
    • Area cropping: If inputStream.area is configured, the image is cropped to that specific region to reduce processing load.

    2. Localization (when locate: true)

    If localization is enabled (which is the default), the engine identifies where the barcode is located in the frame using:

    1. Binarization: Converting the image to black and white using Otsu's method.
    2. Grid division: Splitting the image into smaller patches.
    3. Skeletonization: Extracting line structures.
    4. Pattern analysis: Searching for patterns that resemble barcodes.
    5. Bounding box: Calculating the specific region containing the barcode.

    3. Decoding

    Once the barcode region is identified, the engine performs:

    1. Scanline extraction: Sampling pixels along the detected barcode.
    2. Pattern matching: Comparing bar/space patterns against the specific barcode format.
    3. Character decoding: Converting those patterns into text characters.
    4. Checksum validation: Verifying the integrity of the decoded data.
  6. Register and use external reader modules

    master

    Quagga2 allows you to extend its capabilities by registering external reader modules. Once registered via Quagga.registerReader(), you can include the custom reader in your configuration's decoder.readers array. The order in the array determines the priority (which reader attempts to decode first).

    // Register external reader first
    Quagga.registerReader('my_custom_reader', MyCustomReader);
    
    // Use in config - position determines priority
    Quagga.init({
        decoder: {
            // External reader tried first, then built-in readers
            readers: ['my_custom_reader', 'ean_reader', 'code_128_reader']
        }
    });
  7. Understand TypeScript type resolution for `gl-matrix`

    master

    If you are using Quagga2 with TypeScript, you may notice that gl-matrix is listed as a direct dependency rather than a development dependency. This is because the Quagga2 type definitions (type-definitions/quagga.d.ts) import vec2 from gl-matrix to provide typing for the Moment.vec property.

    import { vec2 } from 'gl-matrix';
    
    export type Moment = {
        // ... other properties
        vec?: vec2;
    };

    Because of this import, TypeScript consumers need gl-matrix installed in their own project to resolve these types during compilation. While the gl-matrix runtime code is bundled into the production files (dist/quagga.min.js), the package is required for successful type checking.

    import { vec2 } from 'gl-matrix';
    
    export type Moment = {
        // ... other properties
        vec?: vec2;
    };
  8. Understand the Quagga2 data flow

    master

    Quagga2 processes barcode detection through a linear pipeline that transforms raw input into a decoded result. The flow follows these stages:

    1. Camera/Image: The raw source.
    2. FrameGrabber: Captures a specific frame from the source.
    3. ImageWrapper: Performs necessary preprocessing, such as grayscale conversion.
    4. BarcodeLocator: Identifies the specific region in the image where a barcode is located.
    5. BarcodeDecoder: Analyzes the localized region to decode the barcode data.
    6. Result callbacks: Triggers user-defined handlers (like onDetected) with the final result.
  9. Configure the QuaggaJS configuration object

    master

    The QuaggaJS configuration is managed via a config object that controls localization, input sources, scan frequency, decoding logic, and localization behavior.

    Key top-level properties include:

    • locate: Boolean. Enables or disables the ability to find a barcode within an image (default: true).
    • inputStream: Object. Defines the source of images/videos.
    • frequency: Number. The maximum number of scans per second (optional). This is a maximum limit; the system will scan as fast as CPU allows if it cannot meet this rate.
    • decoder: Object. Configures how barcodes are converted into data.
    • locator: Object. Configures the localization process (only relevant if locate: true).
    • debug: Boolean. Enables general debugging.
    {
      locate: true,
      inputStream: {...},
      frequency: 10,
      decoder:{...},
      locator: {...},
      debug: false,
    }
  10. Use the CameraAccess API for direct camera control

    master

    The Quagga.CameraAccess API provides direct control over camera functionality, allowing you to manage permissions, enumerate devices, and control hardware features like the torch (flash) independently of the main Quagga initialization. All methods return Promises.

    Key Capabilities:

    • Request and release camera access
    • Enumerate available video devices
    • Control camera torch (flash)
    • Access active MediaStream and MediaStreamTrack objects
    // Access via Quagga.CameraAccess
    await Quagga.CameraAccess.request(videoElement, constraints);
  11. Understand Quagga2 input stream types

    master

    Quagga2 supports three distinct input stream types for barcode reading. Choosing the right type depends on your source media:

    • LiveStream: Used for real-time scanning via a device camera. It uses getUserMedia() and requires HTTPS in production.
    • VideoStream: Used for scanning pre-recorded video files via a <video> element.
    • ImageStream: Used for scanning static images or a sequence of images via URLs. It handles EXIF orientation automatically.

    All stream types implement the same InputStream interface and follow a common asynchronous initialization flow.

    | Type | Use Case | Input Source |
    |------|----------|--------------|
    | **LiveStream** | Real-time camera scanning | Device camera via getUserMedia |
    | **VideoStream** | Pre-recorded video files | Video file via `<video>` element |
    | **ImageStream** | Static images or image sequences | Image file(s) via URL |
  12. Understand Quagga2 operating modes and browser requirements

    master

    Quagga2 supports two primary operating modes, each with different Web API requirements:

    1. Static Image Mode: Used for processing existing image files. Requires support for Canvas, Typed Arrays, Blob URLs, and Blob Builder.
    2. Live Stream Mode: Used for decoding images from a live video stream via a camera. Requires all APIs from Static Image Mode, plus the MediaDevices API for camera access.

    For full compatibility, ensure your target browsers support these APIs. Internet Explorer 11 and below do not support the MediaDevices API and cannot use live camera features.