Skip to content

Barcode Reader Node ​

Overview ​

The Barcode Reader is a multi-decoder node that scans barcodes and QR codes from images using four decoders: ZBar, ZXing, Quagga2 and, since 1.4.0, the Rosepetal SDK engine. It features a flexible block-based architecture that allows you to optimize detection for either maximum accuracy or performance.

Part of the @rosepetal/node-red-contrib-barcode package (@rosepetal/node-red-contrib-barcode-reader up to 1.5.2). The node appears under the RP Utils category in the Node-RED palette.

Architecture ​

The node is made of three parts:

  • barcode-engine/ -- Native C++ addon (Node-API) that wraps ZBar, ZXing, and OpenCV. Since v1.2.1 the preprocessing and the ZBar and ZXing decoding run on async workers, off the Node-RED event loop. Turning the input into an image (copying a bitmap, decoding a JPEG/PNG buffer) runs on the event loop before each call.
  • node-red-contrib-barcode-reader/ -- Node-RED wrapper that provides the editor UI, block configuration, execution modes, and result merging/deduplication. Quagga2 runs here, in JavaScript, on the event loop.
  • node-red-contrib-barcode-reader/lib/rp-mapping.js + the npm dependency @rosepetal/barcode-engine-client -- the rosepetal decoder (v1.4.0+): the client runs rp-barcode serve (a Go binary from the optional @rosepetal/barcode-engine-* packages) as one child process per Node-RED runtime, shared by every barcode-reader node; rp-mapping.js translates a block's options into the engine's decode options and the engine's symbols into the raw results the node already merges.

Prebuilt binaries for barcode-engine are available for linux-x64, linux-arm64, and linuxmusl-x64. On other platforms, the first time a barcode-reader node loads, the package builds the addon from its barcode-engine/ sources (npm run rebuild) when the ZBar, ZXing and OpenCV headers and node-gyp are present; otherwise the node fails to load with Could not load the barcode native addon (see Troubleshooting).

Key Features ​

  • Multi-decoder support: ZBar, ZXing, Quagga2 and the Rosepetal SDK engine
  • Native decoding off the event loop: the addon's preprocessing and the ZBar and ZXing decoders run on C++ async workers (v1.2.1+); the Rosepetal SDK engine runs in its own process
  • Flexible preprocessing: Original, Histogram Equalization, Otsu Threshold, Sharpen
  • Per-block format filter: restrict each block to specific symbologies (e.g. UPC-A only) for speed and to eliminate false positives
  • Block-based configuration: Combine decoders and preprocessing methods
  • Execution modes: Parallel (maximum detection) or Sequential (optimized performance)
  • Batch processing: Process single images or arrays of images
  • Smart deduplication: Automatically merges duplicate detections
  • Performance tracking: Built-in execution time monitoring
  • Rich output format: Includes barcode corners, rotation, and detection metadata

Installation ​

bash
npm install @rosepetal/node-red-contrib-barcode

Up to 1.5.2 the package was @rosepetal/node-red-contrib-barcode-reader (until the first version under the new name is published, the package installs under its old name): on a machine that has it, remove it, install this one and restart Node-RED (npm uninstall @rosepetal/node-red-contrib-barcode-reader && npm install @rosepetal/node-red-contrib-barcode in the Node-RED user dir, then the restart), because both register the same node types, Node-RED refuses the second registration, and a running Node-RED keeps the old types until it restarts. Flows need no change.

npm will attempt to fetch a prebuilt native addon for your platform. Prebuilt binaries bundle OpenCV, ZBar, and ZXing; system libraries are only required for source builds or unsupported platforms.

The optional rosepetal decoder needs the Rosepetal SDK engine. The node depends on @rosepetal/barcode-engine-client (npmjs, published by the SDK), which declares the engine binary as its optional dependencies @rosepetal/barcode-engine-linux-x64 and @rosepetal/barcode-engine-linux-arm64 (client 0.4.0 pins them at 0.4.0; static binary at bin/rp-barcode, the same package for glibc and musl). Those two packages are not on the public npmjs: Rosepetal distributes them from its private npm registry. When the registry npm installs from does not carry them, npm skips them with a warning, every other decoder works as before, and a rosepetal block warns Rosepetal engine not available once per node and returns [].

To add the engine to such a Node-RED, get the platform package as a tarball (npm pack @rosepetal/barcode-engine-linux-x64@0.4.0 against Rosepetal's private registry, run outside the user dir; Rosepetal gives the access) and install it as a tarball kept in the user dir (package.json records its path):

bash
cd ~/.node-red && npm install --no-audit --no-fund ./rosepetal-barcode-engine-linux-x64-0.4.0.tgz

Never run npm install --registry=… inside the user dir (it reconciles the whole tree against that registry), and do not point the @rosepetal scope at the private registry (it does not proxy npmjs: the public client and this package would 404). Alternatively RP_BARCODE_ENGINE=/path/to/rp-barcode points the node at another build of the engine (SDK >= 0.4.0, which the block's defaults need: Projection fallback 0.3.0, Projection retries full 0.4.0; when set it must be executable, the package and PATH are then not searched); as a last resort rp-barcode is looked up in PATH.

Build from source (Debian/Ubuntu) ​

bash
cd node-red-contrib-barcode
bash INSTALL.sh

The script will:

  1. Install ZBar, ZXing, and OpenCV libraries
  2. Build ZXing from source if the package is not available
  3. Build the C++ addon and install the Node-RED package dependencies
  4. Offer to install the package into ~/.node-red when that directory exists

Since 1.4.0 the inner package (node-red-contrib-barcode-reader/package.json, what INSTALL.sh installs) depends on @rosepetal/barcode-engine-client from npmjs; the engine comes from the engine tarball or from RP_BARCODE_ENGINE, as above.

Build dependencies (source builds only) ​

PackagePurpose
libzbar-devZBar barcode library
libzxing-devZXing barcode library (or build from source)
libopencv-devOpenCV image processing
build-essentialC++ compiler toolchain
node-gypNative addon build tool

Runtime requirements ​

  • Node.js: >= 18 (engines.node); the test suite (npm test) needs >= 22.9 because of the node-red 5.0.7 dev dependency
  • Node-RED: >= 1.0.0
  • OS: Linux (Ubuntu/Debian recommended)
  • Rosepetal SDK decoder (optional): the engine package or RP_BARCODE_ENGINE, see above

Configuration ​

Properties ​

Name ​

  • Type: String
  • Default: barcode-reader
  • Description: Name of the node instance; also the key of its entry in msg.performance

Input ​

  • Type: Message property path
  • Default: payload
  • Description: Message property containing the input image(s)

Output ​

  • Type: Message property path
  • Default: payload
  • Description: Message property where results will be stored

Execution Mode ​

  • Type: Select
  • Default: Parallel
  • Options:
    • Parallel: Runs every block and merges their results (maximum detection)
    • Sequential: Runs the blocks in order and returns the results of the first block that reads at least one code (the later blocks do not run)

Decoder Blocks ​

Each block represents a detection attempt with specific configuration. Blocks can be:

  • Added with the "Add Block" button (a new block is ZBar, Original, All formats; a new node has one such block)
  • Reordered by dragging (relevant for Sequential mode)
  • Removed individually
  • Configured independently

The blocks of one image run concurrently in Parallel mode. A block that fails (an option outside its vocabulary, an image the addon refuses, an engine error) warns Block <i> (<decoder>) failed: <reason> and contributes no results; the other blocks still run. <i> counts from 0: Block 1 in the editor is block 0.

Decoder Options ​

ZBar

  • Fast and reliable
  • Good for standard barcodes and QR codes
  • Native C++ implementation via async worker
  • Best overall performance

ZXing

  • Comprehensive format support
  • Thorough scan and rotation handling always enabled (matches zxing.org defaults)
  • Good for damaged or low-quality barcodes
  • Slower but more thorough

Quagga2

  • JavaScript decoder (@ericblade/quagga2, a dependency of the package), loaded only by a node that has a Quagga2 block
  • 1D formats only, and at most one code per image
  • Decodes the block's preprocessed gray image (from the addon) after re-encoding it as a JPEG of quality 85; it runs on the Node-RED event loop
  • The slowest of the decoders

Rosepetal SDK (rosepetal, v1.4.0+)

  • Rosepetal's own engine: the rp-barcode binary of rosepetal-barcode-sdk (Go; 0.4.0 or later for the default settings, see Projection below), run as one persistent rp-barcode serve child process per Node-RED runtime, shared by every barcode-reader node and by barcode-verifier. Pixels go over stdio as raw frames and the decode runs in the engine's process

  • 1D only: UPC-A, UPC-E, EAN-13, EAN-8, Code 128 / GS1-128, Code 39, Code 93, Codabar, ITF. Keep a ZBar/ZXing block for 2D codes; a block whose Formats hold only 2D codes returns [] without calling the engine

  • Editor rows: Projection (Off, Fallback (when nothing reads), Fallback + sharpen retry, Fallback + full retries (default); saved as projection + projectionRetries) and Effort (Normal (default), Robust). Under Advanced: Add-ons (ignore default: the EAN-2/EAN-5 add-on is dropped; read: returned as a separate EAN-2/EAN-5 symbol; require: EAN/UPC symbols without one are dropped), Quiet zone (tolerant default, spec: GS1 / 10X), Min lines (scan lines that must agree; default 0, the per-symbology default), Timeout (ms) (default 5000, 1 to 2147483647; the start of the engine is not counted) and three flags, all off: UPC-A as EAN-13 (13 digits with a leading 0, the 1.1.3 behaviour), Code 39 full ASCII (expand the shift pairs as ZXing blocks do) and Optional checksum (require and verify the Code 39 / ITF / Codabar check character)

  • Flow JSON only (not in the editor; a saved value is kept when the block is edited): directions (both default, horizontal, vertical) and tryInvert (default true), which only apply with Effort normal (robust scans both directions and the inverted image anyway), and edges (Retries, below). tryHarder from older flows is ignored. A value outside the vocabulary, or a number written as a string, fails that block with a warning (rosepetal option <name>: … is not …) and []

  • Effort: robust scans 8 times as many rows, always rows and columns and the inverted image, and retries with the refit gradient: a few more reads (very blurred or 1 px-module codes, inverted or vertical codes) at several times the cost when nothing is found. With Projection on, the engine runs the robust search only after the normal search and the projection read nothing

  • Projection (projection): fallback (default, also for a block saved without it) = when the search of the rows and columns reads nothing, the engine's projection search: it finds the reading direction at any angle, averages bands along the bars into profiles and accepts a value at least 3 of them agree on. It is meant for noisy, blurred or low-resolution crops of one code (it looks for one dominant code: not full frames). off = no projection search, no key sent, any engine. It costs nothing on the images the rows read; on the images they do not read it is the slowest search of the engine, so check the time budget with images of the line that do not read. With fallback and a colour input of at most 1,500,000 pixels (width × height, both sides at least 3 px) the block sends the image in colour (3 channels: RGB/BGR as they are, RGBA/BGRA without alpha, an encoded file decoded to BGR), so the projection can also read the R, G and B planes, in either effort. 1,500,000 pixels is the largest image the engine's projection runs on: a larger frame (a full camera frame such as 2448×2048), a gray input and a block at off send the preprocessed gray. The Preprocessing (Sharpen included) acts on the gray, so it does not apply to a colour frame, and detectedBy then reads rosepetal without a suffix (rosepetal_original with Original). A colour frame is three times the bytes of the gray. Needs rosepetal-barcode-sdk 0.3.0 or later: on an older engine the block warns rosepetal option projection: the installed engine … does not support it (…). Projection "fallback" needs rosepetal-barcode-sdk 0.3.0 or later; set Projection to off to read with this engine and returns []; the other blocks run

  • Projection retries (projectionRetries, the level of the same select): extra passes of the projection search, cumulative. off (the Fallback (when nothing reads) level) = none; sharpen = the band profiles decoded once more, unsharp-masked, for blurred crops (inside the engine, so it also works on the colour frame); full (default, also for a block saved without the option, such as a block of 1.4.0; an explicit off or sharpen stays as saved) = sharpen, then the low-decodability EAN/UPC reads voted again, the band profiles split at the threshold of their histogram (faded narrow bars) and EAN-13 / UPC-A read from any start guard (a quiet zone cut by something dark; not with Quiet zone spec or Add-ons require). They run only with Projection fallback and only when everything before them read nothing, and every value they add is guarded against the EAN/UPC 1↔7 and 2↔8 flips. Choosing Off in the select saves projection: "off" without a level, and no retry key is sent. The composition of the levels is one table, PROJECTION_RETRIES in lib/rp-mapping.js. Measured by the SDK (normal effort, colour planes):

    Levelbarcode_360 (95 verifiable crops)BarBeR devp95 per crop that nothing readsWorst case within 1,500,000 px
    off74 (77.9 %)3352 (81.6 %)92 ms136 ms
    sharpen85 (89.5 %)3409 (83.0 %)109 ms183 ms
    full90 (94.7 %)3465 (84.4 %)168 ms312 ms

    sharpen and full need rosepetal-barcode-sdk 0.4.0 or later: on an older engine the block warns rosepetal option projectionRetries: the installed engine … does not support it (…). Projection "full" needs rosepetal-barcode-sdk 0.4.0 or later; set Projection to Fallback to read with this engine and returns []; the other blocks run

  • Retries (edges, flow JSON only): how a search of the whole image retries the scan rows the row threshold read nothing on. auto (default, also for a block saved without it) = the engine's recommended retries: with Effort robust the histogram threshold and then gradient edges refit to the profile of the row, with normal the histogram threshold alone; histogram = the histogram threshold alone in both efforts; gradient = the refit gradient alone (with robust it reads less than auto); threshold = no retries, the reads and latency of the 0.2.0 engine. The SDK measured the p95 per crop of robust auto at about +44 % over histogram and +134 % over threshold (BarBeR dev). auto sends no key and runs on any engine; any other value needs rosepetal-barcode-sdk 0.3.0 or later: on the 0.2.0 engine the block warns rosepetal option edges: the installed engine … does not support it … and returns []

  • Output adds symbology, identifier (ISO/IEC 15424), orientation (0/90/180/270), lines, confidence, checksum when the base result came from this block; corners are the bar extent (TL, TR, BR, BL) and box.angle is 0 for a horizontal code (ZXing gives ±90 there). format uses ZXing's spelling plus EAN-2/EAN-5 for add-ons read as separate symbols

  • Legacy rp-projection blocks (1.5.1+): the C++ rp-projection decoder of 1.3.0-1.5.0 is gone from the addon and the editor no longer offers it. An rp-projection block in a flow runs as a Rosepetal SDK block with Original, effort: normal, projection: fallback and the default retries (full), with its Formats and its detectedBy name (rp-projection); minVotes and stripWidth are ignored, and the editor opens and saves it as that Rosepetal SDK block (once saved, its reads say rosepetal_original). It sends colour up to 1,500,000 pixels like any block with Projection on. Such a block needs rosepetal-barcode-sdk 0.4.0 or later: with the 0.2.0 engine it warns Block <i> (rp-projection) failed: rosepetal option projection: the installed engine … does not support it … and returns []; the other blocks run

  • Needs the engine package (@rosepetal/barcode-engine-linux-x64 / -linux-arm64, private registry, optional dependencies of the client), RP_BARCODE_ENGINE, or rp-barcode in PATH; without it the block warns Rosepetal engine not available: <reason>. <install hint> once per node and outage and returns []. A running engine that dies is restarted 1 s later by the next request (a binary that fails to start is retried with a growing wait, up to 30 s); the crops of the same message inside that second get []. The engine version is logged once per node at its first use (Rosepetal engine 0.4.0+<commit> (protocol 1, pid N)), and whatever the engine writes to its stderr appears in the Node-RED log as [rp-barcode] … warnings

  • Timing on the development host: about 11-13 ms per 600×300 crop with robust (20 crops in one array: about 220-255 ms); robust on a large full image with no code costs 0.2-0.8 s (the whole scan runs); the first decode after a (re)deploy also pays the engine start

Rosepetal SDK compared with ZBar and ZXing blocks (same msg contract; fields are only added):

  • corners are the bar extent in reading order TL, TR, BR, BL, so box.angle is 0 for a horizontal code (ZXing gives ±90 there) and ±90 for a vertical one; orientation (0/90/180/270, clockwise reading direction) tells 0 from 180. ZBar and ZXing report a 1D code as its scan line (a degenerate box)
  • detectedBy has one entry per block that read the value, so a Rosepetal-only flow gives length 1: use lines (agreeing scan lines) and confidence (0-1) as the confidence instead of the number of blocks
  • UPC-A comes out as 12 digits (UPC-A); UPC-A as EAN-13 gives the 13-digit form of 1.1.3
  • UPC-E comes out as its 8 digits (UPC-E), as ZXing prints it; ZBar blocks print the 12-digit UPC-A expansion (see Deduplication Logic for mixed flows)
  • Code 39 shift pairs are returned as printed unless Code 39 full ASCII is on (ZXing blocks always expand them)
  • GS1-128 values carry the FNC1 separators as the character \u001d (GS) and no leading FNC1; ZXing blocks print the human-readable (01)…(10)… form instead, so templates saved from a ZXing block need re-saving or a match without the parentheses
  • When several blocks read the same value, the geometry and the extra fields come from the lowest block: put the Rosepetal SDK block first to get orientation, lines and the bar corners in the output

Preprocessing Options ​

Original

  • Simple grayscale conversion
  • Fastest option
  • Use for high-quality images with good contrast

Histogram Equalization

  • Enhances contrast across the image
  • Good for poor lighting conditions
  • Helps with uneven illumination

Otsu Threshold

  • Histogram equalization, then a binary (black/white) image with Otsu's threshold
  • Best for low-contrast barcodes
  • Effective for faded or worn codes

Sharpen (1.5.0)

  • Unsharp mask: gray + amount × (gray − GaussianBlur(gray, sigma)), computed in float and saturated to 8 bits
  • For blurred or out-of-focus codes (the bottle turning under a line-scan camera, curved labels): it restores the contrast of the narrow bars and spaces that blur flattens below a global threshold
  • Sharpen sigma (default 2 px, (0, 20]): about the width of one narrow bar in pixels; Sharpen amount (default 1.5, (0, 10]): the strength. Both are under the block's Advanced section, shown when Preprocessing is Sharpen. Saved in the block as preprocessingOptions: { sigma, amount }; the editor saves an empty or out-of-range value as the default, while a hand-edited value out of range fails the block with a warning
  • Applies to ZBar, ZXing, Quagga2 and Rosepetal SDK blocks; not to the colour frame a Rosepetal SDK block sends with Projection fallback for a colour input of at most 1,500,000 pixels (a gray input of that block, or a larger frame, is sharpened)
  • Caution: with ZBar use it only for EAN/UPC (ZBar stops reading clean Code 128, Code 39, Code 93, Codabar and ITF symbols once they are sharpened; ZXing and the Rosepetal SDK keep reading them), and check the wrong reads on your own images before using a stronger mask in production
  • Needs the 1.5.0 addon: with an older addon a Sharpen block fails with a warning that says so

Format Filter (per block) ​

Each block has a Formats allowlist. The list shown in the editor is filtered to formats the selected decoder actually supports — so you'll see different options when the block uses ZBar vs. ZXing vs. Quagga2 (Quagga2 and the Rosepetal SDK are 1D-only).

  • All formats (default): the decoder is unrestricted; current behavior is preserved.
  • Specific formats: only the checked symbologies are decoded. Useful for reducing false positives in production lines that scan a single known format. With ZBar, a list that holds EAN13 without UPCA reads a UPC-A code as a 13-digit EAN-13 with a leading 0 (see Troubleshooting).

Selections persist across decoder changes when the new decoder still supports them — for example switching a block from ZBar to ZXing with UPCA checked keeps UPCA checked; switching to Quagga2 from ZXing with Aztec checked drops Aztec (Quagga2 is 1D-only).

Input Format ​

The node accepts images in multiple formats:

Rosepetal Bitmap Format ​

javascript
{
  data: Buffer,            // Raw pixel data
  width: 1920,
  height: 1080,
  colorSpace: "RGB",       // "GRAY", "RGB", "BGR", "RGBA", "BGRA"
  dtype: "uint8"
}

colorSpace is written in capitals as above; dtype, when present, must be "uint8"; data.length must equal width × height × channels.

Raw Bitmap ​

javascript
{
  width: 1920,
  height: 1080,
  data: Buffer,
  channels: 3              // 1 (grayscale), 3 (taken as RGB), 4 (taken as RGBA)
}

Without colorSpace and channels, the channels are inferred from data.length (1, 3 or 4 bytes per pixel). Send BGR or BGRA data with colorSpace. Width and height are at most 32768 px.

Image Buffers ​

  • JPEG buffer
  • PNG buffer

The prebuilt addon's OpenCV also decodes BMP and WebP (not TIFF); a source build decodes what the system's OpenCV supports. An encoded buffer is decoded again by every block, on the event loop: with several blocks, a raw bitmap saves that work.

Array Input ​

Process multiple images at once:

javascript
msg.payload = [image1, image2, image3];

The images are processed one after another, each through every block.

Invalid input ​

  • msg.<Input> missing (or empty): the message fails with Input path "<path>" not found in msg.
  • An input without width and height that is not a decodable image buffer: the message fails with Could not determine image dimensions (in an array, one such image fails the whole message).
  • A bitmap with width and height that the addon refuses (an unknown colorSpace, a data.length that does not match): every block warns Block <i> (<decoder>) failed: … with the addon's reason, and the result is [].

Output Format ​

format has one spelling whatever block read the code, ZXing's (the Rosepetal SDK block prints it too): EAN-13, EAN-8, UPC-A, UPC-E, Code128, Code39, Code93, Codabar, ITF, QRCode, DataMatrix, PDF417, Aztec, DataBar, DataBarExpanded, and EAN-2 / EAN-5 for add-ons. ZBar (CODE-128, I2/5, QR-Code…) and Quagga2 (code_128, ean_13…) names are mapped onto it.

Single Image Input ​

Returns an array of detected barcodes:

javascript
[
  {
    format: "QRCode",
    value: "decoded_content_here",
    box: {
      center: { x: 0.5, y: 0.5 },        // Relative coordinates (0-1)
      size: { width: 0.2, height: 0.2 },  // Relative to image size
      angle: 15                            // Rotation in degrees
    },
    corners: [                             // Four corners in relative coordinates
      { x: 0.4, y: 0.4 },
      { x: 0.6, y: 0.4 },
      { x: 0.6, y: 0.6 },
      { x: 0.4, y: 0.6 }
    ],
    detectedBy: ["zbar_original", "zxing_original"] // Which decoder/preprocessing found it: one string per block
  }
]

detectedBy is an array of "<decoder>_<preprocessing>" strings, one per block that read the value (rp-projection alone for a legacy projection block, rosepetal alone for a Rosepetal SDK block that sent colour and so skipped its Histogram, Otsu or Sharpen). When the base result came from a rosepetal block (v1.4.0+) the object also carries symbology, identifier, orientation, lines, confidence and checksum; results of the other decoders never have them.

The order of corners and the meaning of box.angle depend on the block the base result came from: see Rosepetal SDK compared with ZBar and ZXing blocks. Quagga2 reports at most one code per image, and a Quagga2 read without a box has all its corners at 0.

Array Input ​

Returns nested array structure:

javascript
[
  [image1_result1, image1_result2], // Results from first image
  [image2_result1],                  // Results from second image
  []                                 // No results from third image
]

Coordinate System ​

All coordinates are normalized to 0-1 range:

  • x: 0 = left edge, x: 1 = right edge
  • y: 0 = top edge, y: 1 = bottom edge

To convert to pixels: pixelX = x * imageWidth

Performance Tracking ​

The node adds its execution time to msg.performance, under the node's Name (barcode-reader by default):

javascript
msg.performance = {
  "barcode-reader": {
    startTime: Date,       // when the message arrived (a Date object)
    milliseconds: 245      // the time of the whole message, every image and block included
  }
}

Status and Errors ​

SituationNode statusWhat happens
Message processed<ms> msThe message is sent with the results (an empty array when nothing is read)
A block fails<ms> msWarning Block <i> (<decoder>) failed: <reason>; that block gives no results, the other blocks run (Sequential: the next block runs)
A Rosepetal SDK block without engine<ms> msWarning Rosepetal engine not available: … once per node and outage; the block gives []
No blocks configured<ms> msWarning No decoder blocks configured; the result is []
The message failsred ring ErrorThe error goes to a Catch node and nothing is sent: Input path "<path>" not found in msg., Could not determine image dimensions

Usage Examples ​

Example 1: Maximum Detection Rate (Parallel Mode) ​

Use case: Scanning worn, damaged, or low-quality barcodes

Configuration:

  • Mode: Parallel
  • Block 1: ZBar + Original
  • Block 2: ZBar + Histogram Equalization
  • Block 3: ZBar + Otsu Threshold
  • Block 4: ZXing + Original
  • Block 5: ZXing + Histogram

Behavior: All blocks run concurrently (ZBar and ZXing on the addon's async workers), results are merged and deduplicated.

Trade-off: Higher total CPU time, maximum detection rate

Example 2: Fast with Fallback (Sequential Mode) ​

Use case: High-throughput production with mostly good quality codes

Configuration:

  • Mode: Sequential
  • Block 1: ZBar + Original (fastest)
  • Block 2: ZXing + Original (if Block 1 fails)
  • Block 3: ZXing + Histogram (last resort)

Behavior: Stops at first successful detection

Trade-off: Fast for most images, reliable fallback for difficult ones

Example 3: Balanced Approach ​

Use case: Mixed quality images, moderate performance requirements

Configuration:

  • Mode: Parallel
  • Block 1: ZBar + Original
  • Block 2: ZXing + Histogram
  • Block 3: Quagga2 + Otsu

Behavior: Three different approaches run in parallel

Trade-off: Good balance of speed and detection rate

Example 4: Processing Multiple Images ​

javascript
// Input node
msg.payload = [
  imageBuffer1,
  imageBuffer2,
  imageBuffer3
];

// After barcode reader
msg.payload = [
  [{ format: "QRCode", value: "ABC123", ... }],   // Results from image 1
  [{ format: "Code128", value: "XYZ789", ... }],  // Results from image 2
  []                                               // No barcodes in image 3
];

Example 5: Custom Input/Output Paths ​

javascript
// Configuration:
// - Input: "image"
// - Output: "barcodes"

msg.image = {
  data: pixelBuffer,       // raw pixels, 1920 × 1080 × 3 bytes
  width: 1920,
  height: 1080,
  colorSpace: "BGR"
};

// After processing:
msg.barcodes = [
  { format: "QRCode", value: "scanned_data", ... }
];

Supported Barcode Formats ​

1D Barcodes ​

  • CODE-128 (logistics, shipping)
  • CODE-39 (automotive, DoD)
  • CODE-93 (Canada Post)
  • EAN-13 (retail products worldwide)
  • EAN-8 (small retail items)
  • UPC-A (North America retail)
  • UPC-E (small packages)
  • CODABAR (libraries, blood banks, FedEx)
  • ITF (Interleaved 2 of 5)
  • GS1 DataBar (ZBar and ZXing blocks only; reported as DataBar or DataBarExpanded)

2D Barcodes ​

  • QR Code
  • Data Matrix
  • PDF417
  • Aztec Code

Decoder Format Support ​

The canonical names match the values used in each block's Formats filter.

Canonical nameZBarZXingQuagga2Rosepetal SDK
UPCAYYYY
UPCEYYYY
EAN13YYYY
EAN8YYYY
Code128YYYY
Code39YYYY
Code93YYYY
CodabarYYYY
ITFYYYY
QRCodeYY--
PDF417YY--
DataMatrix-Y--
Aztec-Y--
DataBarYY--

Formats not supported by a decoder are omitted from the editor's checklist when that decoder is selected; if a Format is set programmatically that the decoder doesn't support, it is silently ignored. A list that holds no name the decoder knows makes ZBar, Quagga2 and the Rosepetal SDK return nothing, and ZXing read every format.

Performance Considerations ​

Async Processing (v1.2.1+) ​

The addon's preprocessing and the ZBar and ZXing decoders run on C++ async workers (the libuv thread pool), and the Rosepetal SDK decodes in its own process. So several blocks and messages can be in flight at once, and other nodes keep processing messages while those decoders run. What still runs on the Node-RED event loop:

  • turning the input into an image before each addon call: copying a bitmap, or decoding a JPEG/PNG buffer (once per block, plus once to learn its size)
  • Quagga2 (JavaScript), including the JPEG encoding of its input
  • merging and deduplicating the results

Execution Time Factors ​

  1. Number of blocks: More blocks = longer execution (in Parallel mode)
  2. Preprocessing method: Original < Histogram < Otsu < Sharpen (a float Gaussian: its cost grows with sigma; about 2 ms on a 600×300 crop and 27 ms on a 2448×2048 image at sigma 2)
  3. Decoder choice: ZBar < ZXing < Quagga2 (approximate; Quagga2 is the slow JavaScript path). The Rosepetal SDK is measured per crop in Decoder Options above (about 11-13 ms per 600×300 crop with robust, less with normal): with robust it is slower than ZBar and ZXing (20-25× zxing-cpp per crop in the SDK benchmarks), more so on a large image with no code
  4. Image size: Larger images take longer (the Rosepetal SDK projection, when it runs, scales with crop height × width)

Optimization Strategies ​

For Speed ​

  • Use Sequential mode
  • Start with Original preprocessing
  • Place fastest blocks first (ZBar + Original)
  • Reduce image resolution before processing
  • Use single decoder only
  • With several blocks, send a raw bitmap rather than a JPEG/PNG buffer (an encoded buffer is decoded once per block)

For Accuracy ​

  • Use Parallel mode
  • Include multiple preprocessing options
  • Use multiple decoders
  • Ensure good image quality (1500px max on long side recommended)

Deduplication Logic ​

When multiple blocks detect the same barcode:

  1. Barcodes are considered duplicates if they have the same value (data) at the same place: the boxes overlap along the code and lie within half its length across it. The same value printed twice (two labels side by side) gives two results; a detection without a box (Quagga2 without one) joins the first detection of its value
  2. The detection from the lowest block index is kept as the primary result
  3. All detection methods are tracked in the detectedBy array
  4. Position data (corners, box) comes from the primary detection, and so do the Rosepetal SDK fields (symbology, identifier, orientation, lines, confidence, checksum) when the primary is a rosepetal block
  5. Two different values whose boxes lie on top of each other (spatial deduplication, typically a ghost read on a blurry scan line) are one symbol: the value more blocks agree on wins; with as many blocks on each side, the read that came first (the lowest block) stays, except between reads of the same decoders, where the taller box wins. Codes stacked on a label do not overlap and all come out
  6. The spatial rule also decides between two spellings of one symbol. UPC-E: ZXing and the SDK print the 8 digits, ZBar the 12-digit UPC-A expansion, so in a flow mixing them the block order and count decide which form is printed, and a template saved with the other form stops matching. A GS1-128 keeps only one form (ZXing's HRI or the SDK's \u001d separators, whichever block is lower). A flow without a rosepetal block is unchanged

Example:

javascript
// Block 0: ZBar + Original detects "ABC123"
// Block 2: ZXing + Histogram also detects "ABC123"

// Result:
{
  format: "Code128",
  value: "ABC123",
  box: { /* from Block 0 */ },
  corners: [ /* from Block 0 */ ],
  detectedBy: ["zbar_original", "zxing_histogram"]
}

Programmatic API ​

The barcode-engine addon can be used outside Node-RED. All native functions are async (callback-based) and are promisified by the package:

javascript
const barcode = require('@rosepetal/node-red-contrib-barcode');

// Preprocessing (returns grayscale image as Rosepetal bitmap)
const gray     = await barcode.preprocess_original(inputMat);
const enhanced = await barcode.preprocess_histogram(inputMat);
const binary   = await barcode.preprocess_otsu(inputMat);
const sharp    = await barcode.preprocess_sharpen(inputMat, { sigma: 2, amount: 1.5 });  // options optional; sigma (0, 20] px, amount (0, 10]

// Decoders (require grayscale input, return JSON string)
// Signature: decode_zbar(image, formats)
const zbarAll  = await barcode.decode_zbar(gray, []);                 // all symbologies
const zbarUpc  = await barcode.decode_zbar(gray, ['UPCA']);           // UPC-A only

// Signature: decode_zxing(image, formats)
const zxAll    = await barcode.decode_zxing(gray, []);          // all formats
const zxQrOnly = await barcode.decode_zxing(gray, ['QRCode']);  // QR only

// Parse results
const { results } = JSON.parse(zbarUpc);

// Utilities
const resized   = await barcode.resizeImage(inputMat, 50);   // 50% size, percentage in (0, 100]
const converted = await barcode.convertToMat(jpegBuffer);    // an encoded buffer as a bitmap (BGR, BGRA or GRAY)

formats argument: an array of canonical format names (see the Decoder Format Support table). Pass [] to leave the decoder unrestricted. Unsupported names for a given decoder are silently ignored.

Every function takes a bitmap or an encoded buffer, as the node does. Wrong arguments reject the promise (for example Second argument (formats) must be an array of strings). Given an image with more than one channel, decode_zbar and decode_zxing resolve with {"error": "Expected grayscale image (1 channel)"} instead of rejecting: preprocess first.

Decoder Result Format ​

javascript
{
  "results": [
    {
      "type": "QR-Code",           // the decoder's own spelling (ZBar here; ZXing writes "QRCode")
      "data": "decoded content",
      "quality": 1,                // ZBar's quality, or ZXing's line count
      "points": {                  // pixels
        "x1": 100, "y1": 100,
        "x2": 200, "y2": 100,
        "x3": 200, "y3": 200,
        "x4": 100, "y4": 200
      }
    }
  ]
}

Troubleshooting ​

No Barcodes Detected ​

Possible causes:

  • Barcode too small or large in image
  • Poor image quality or low contrast
  • Barcode damaged or partially obscured
  • Unsupported barcode format

Solutions:

  1. Add blocks with stronger preprocessing (Histogram, Otsu)
  2. Add a ZXing block alongside ZBar (different decoders catch different cases)
  3. Switch to Parallel mode for comprehensive scanning
  4. Verify barcode format is supported
  5. Check image quality and resolution
  6. Ensure proper lighting in source images

Build Errors ​

These errors only apply to source builds (when no prebuilt binary is available for your platform).

"Could not load the barcode native addon"

  • No prebuilt package loaded and the automatic build did not run or failed (it runs only when the ZBar, ZXing and OpenCV headers and node-gyp are present). Install the system dependencies, build the addon in the barcode-engine/ directory of the installed package with npm install (it installs node-addon-api and runs node-gyp rebuild, as INSTALL.sh does), then restart Node-RED

"Cannot find -lzbar"

bash
sudo apt-get install libzbar-dev

"Cannot find -lZXing"

bash
# Build ZXing from source
git clone https://github.com/zxing-cpp/zxing-cpp.git
cd zxing-cpp && git checkout v2.3.0
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=/usr -DBUILD_SHARED_LIBS=ON ..
make -j$(nproc) && sudo make install
sudo ldconfig

"Cannot find opencv2/opencv.hpp"

bash
sudo apt-get install libopencv-dev

node-gyp errors

bash
sudo apt-get install build-essential python3
npm install -g node-gyp

Slow Performance ​

Possible causes:

  • Too many blocks in Parallel mode
  • Large image resolution
  • Many ZXing blocks (slower than ZBar)
  • Processing arrays of many images

Solutions:

  1. Switch to Sequential mode
  2. Reduce number of blocks
  3. Prefer ZBar blocks for cases ZBar can handle on its own
  4. Resize images before processing
  5. Remove blocks with slow preprocessing (Otsu)

Wrong Barcode Values ​

Possible causes:

  • Multiple barcodes in image
  • Barcode partially damaged
  • Similar patterns confusing decoder

Solutions:

  1. Crop image to single barcode region
  2. Use stronger preprocessing
  3. Verify expected barcode format

UPC-A read as EAN-13 with leading 0 ​

ZBar treats UPC-A as a subset of EAN-13. An unrestricted ZBar block (All formats) enables UPC-A explicitly and reports such a code as UPC-A (12 digits); a ZBar block whose Formats list holds EAN13 without UPCA reports it as a 13-digit EAN-13 with a leading 0.

Solution: add UPCA to the block's Formats list (enable both UPCA and EAN13 if you need both). If your templates hold the 13-digit form (saved with 1.1.3), a Rosepetal SDK block has UPC-A as EAN-13.

Missing Quagga2 Warning ​

Message (when a node with a Quagga2 block starts): Quagga2 not available (<reason>). Install @ericblade/quagga2 to use Quagga decoder. Each Quagga2 block of that node then warns Block <i> (quagga2) failed: Quagga2 is not installed on every message.

Solution: @ericblade/quagga2 is a dependency of the package, so the reason says what failed to load. Reinstall the package, or install the module in the Node-RED user dir:

bash
cd ~/.node-red && npm install @ericblade/quagga2

Or remove Quagga2 blocks from configuration.

rosepetal block returns [] with "Rosepetal engine not available" ​

The engine package is missing (no access to the private registry at install time), RP_BARCODE_ENGINE is set to something that is not executable, or the binary speaks another protocol (too old or too new for this node version). Check ~/.node-red/node_modules/@rosepetal/barcode-engine-linux-x64/bin/rp-barcode version (prints rp-barcode 0.4.0 (schema 1.0, GS1 Syntax Dictionary …, build <rev>)), reinstall as described under Installation, and redeploy. The warning is printed once per node and outage; the other blocks of the node keep working.

rosepetal block times out or reports "engine exited" ​

Raise Timeout for very large images or switch Effort to normal. After a crash the block returns [] for 1 s (every crop of the same message inside that wait included) and the first message after the wait is read by the new process. The engine's own messages appear as [rp-barcode] … warnings in the Node-RED log.

Rosepetal SDK block: "the installed engine … does not support it" ​

The installed engine is older than an option the block sends, and the warning names it: Projection Fallback needs rosepetal-barcode-sdk 0.3.0, its sharpen and full retries (the default) 0.4.0, and a flow-JSON edges other than auto 0.3.0. Choose a lower Projection level (Off runs on any engine) or install a newer engine. The engine keeps running and the warning repeats on every message.

Values changed after adding a rosepetal block ​

UPC-E (8 digits instead of the 12-digit UPC-A expansion, depending on which block comes first) and GS1-128 (\u001d separators or ZXing's HRI, depending on block order) are expected: see Deduplication Logic and Rosepetal SDK compared with ZBar and ZXing blocks. A downstream filter on detectedBy.length >= 2 drops every read of a Rosepetal-only flow: use lines / confidence instead.

Best Practices ​

Image Preparation ​

  1. Resolution: Keep images around 1500px on the long side for optimal balance
  2. Format: Use JPEG for photos, PNG for generated codes
  3. Lighting: Ensure even lighting across barcode
  4. Focus: Barcodes must be sharp and in focus
  5. Orientation: the rotation is reported in box.angle; for 1D codes tilted well away from horizontal or vertical, add a Rosepetal SDK block with Projection on (its projection search reads at any angle)

Block Configuration ​

  1. Start simple: Begin with 1-2 blocks and add more if needed
  2. Order matters: In Sequential mode, put fastest/most likely blocks first
  3. Test thoroughly: Verify with representative sample images
  4. Monitor performance: Watch execution times in production
  5. Document choices: Note why specific blocks were chosen

Production Deployment ​

  1. Test all formats: Verify all expected barcode types are detected
  2. Benchmark performance: Measure actual execution times
  3. Handle failures: Implement proper error handling for no-detection cases
  4. Log statistics: Track detection rates and performance
  5. Version control: Document block configuration changes

Advanced Usage ​

Block Configuration in the Flow JSON ​

The blocks are part of the node's configuration: the node reads no configuration from the message. In an exported flow they look like this:

json
{
  "type": "barcode-reader",
  "name": "barcode-reader",
  "inputValue": "payload",
  "outputValue": "payload",
  "executionMode": "sequential",
  "blocks": [
    { "decoder": "zbar",  "preprocessing": "original",  "options": { "formats": ["UPCA"] } },
    { "decoder": "zxing", "preprocessing": "histogram", "options": { "formats": [] } },
    { "decoder": "zxing", "preprocessing": "sharpen",   "options": { "formats": [] },
      "preprocessingOptions": { "sigma": 2, "amount": 1.5 } }
  ]
}

options.formats is an array of canonical format names (see Decoder Format Support). Use [] or omit the key for "all formats". A Rosepetal SDK block keeps its options (projection, projectionRetries, effort, addOn, quietZone, minLines, timeoutMs, upcaAsEan13, code39FullAscii, checksum) in the same options object.

Region of Interest Processing ​

Crop image to barcode region before processing, for example with sharp in a function node (add sharp under Setup → Modules of the function node, imported as sharp; it is not a dependency of this package):

javascript
// In a function node before the barcode reader
msg.payload = await sharp(msg.payload)
  .extract({ left: 100, top: 100, width: 500, height: 200 })
  .toBuffer();
return msg;

The coordinates of the results are then relative to the crop.

Quality Validation ​

Filter results by confidence or validation:

javascript
// In a function node after the barcode reader
msg.payload = msg.payload.filter(result => {
  // Only keep results detected by multiple methods
  return result.detectedBy.length >= 2;
});

Performance Monitoring ​

Track detailed performance metrics:

javascript
// In a function node after the barcode reader (the key is the node's Name, "barcode-reader" by default)
const perf = msg.performance["barcode-reader"];
const detectionCount = Array.isArray(msg.payload) ? msg.payload.length : 0;

msg.metrics = {
  executionTime: perf.milliseconds,
  detectionsFound: detectionCount,
  detectionsPerSecond: (detectionCount / perf.milliseconds * 1000).toFixed(2)
};

Migration Guide ​

From node-zbardecoder ​

If migrating from the basic node-zbardecoder package:

Old approach:

javascript
const bardecoder = require('node-zbardecoder');
const result = JSON.parse(bardecoder.decode('image.jpg'));

New approach:

  • Use the Barcode Reader node in your flow
  • Configure with ZBar decoder + Original preprocessing
  • Results are automatically parsed and formatted
  • Additional decoders and preprocessing available

Key differences:

  • Block-based configuration vs. single decoder
  • Relative coordinates instead of absolute pixels
  • Rich metadata (corners, rotation, detection tracking)
  • Built-in performance monitoring
  • Native decoding on async workers, off the event loop

See Also ​