@rosepetal/node-red-contrib-image-tools 1.6.4 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/.claude/rules/node-implementation-template.md +1 -1
  2. package/.github/workflows/build-prebuild.yml +1 -1
  3. package/README.md +41 -21
  4. package/docs/index.md +156 -0
  5. package/docs/nodes/blend/add-bbs.md +116 -0
  6. package/docs/nodes/blend/add-mask.md +67 -224
  7. package/docs/nodes/blend/add-masks.md +74 -196
  8. package/docs/nodes/blend/blend.md +84 -200
  9. package/docs/nodes/io/folder-in.md +92 -0
  10. package/docs/nodes/io/image-in.md +61 -52
  11. package/docs/nodes/io/image-out.md +114 -93
  12. package/docs/nodes/mix/advanced-mosaic.md +124 -78
  13. package/docs/nodes/mix/concat.md +71 -56
  14. package/docs/nodes/mix/mosaic.md +81 -91
  15. package/docs/nodes/specialized/cropBB.md +76 -214
  16. package/docs/nodes/specialized/heat-diff.md +111 -0
  17. package/docs/nodes/specialized/image-align.md +125 -387
  18. package/docs/nodes/transform/color-convert.md +101 -0
  19. package/docs/nodes/transform/crop.md +56 -58
  20. package/docs/nodes/transform/draw.md +46 -26
  21. package/docs/nodes/transform/filter.md +110 -46
  22. package/docs/nodes/transform/padding.md +55 -55
  23. package/docs/nodes/transform/resize.md +81 -56
  24. package/docs/nodes/transform/rotate.md +67 -50
  25. package/node-red-contrib-image-tools/lib/bmp-decode.js +18 -68
  26. package/node-red-contrib-image-tools/lib/cpp-bridge.js +202 -104
  27. package/node-red-contrib-image-tools/lib/node-utils.js +78 -78
  28. package/node-red-contrib-image-tools/nodes/io/folder-in.js +98 -46
  29. package/node-red-contrib-image-tools/nodes/io/image-in.js +3 -4
  30. package/node-red-contrib-image-tools/nodes/io/image-out.js +93 -146
  31. package/node-red-contrib-image-tools/nodes/specialized/cropBB.js +3 -3
  32. package/node-red-contrib-image-tools/nodes/specialized/heat-diff.js +3 -3
  33. package/node-red-contrib-image-tools/nodes/specialized/image-align.html +11 -4
  34. package/node-red-contrib-image-tools/nodes/specialized/image-align.js +5 -4
  35. package/node-red-contrib-image-tools/nodes/transform/color-convert.js +3 -3
  36. package/node-red-contrib-image-tools/nodes/transform/crop.js +3 -3
  37. package/node-red-contrib-image-tools/nodes/transform/filter.js +3 -3
  38. package/node-red-contrib-image-tools/nodes/transform/padding.js +3 -3
  39. package/node-red-contrib-image-tools/nodes/transform/resize.js +3 -3
  40. package/node-red-contrib-image-tools/nodes/transform/rotate.js +3 -3
  41. package/npm/darwin-arm64/package.json +1 -1
  42. package/npm/darwin-x64/package.json +1 -1
  43. package/npm/linux-arm64/package.json +1 -1
  44. package/npm/linux-x64/package.json +1 -1
  45. package/npm/linuxmusl-x64/package.json +1 -1
  46. package/npm/win32-x64/package.json +1 -1
  47. package/package.json +6 -6
  48. package/rosepetal-image-engine/binding.gyp +2 -1
  49. package/rosepetal-image-engine/src/add-bbs.cpp +123 -123
  50. package/rosepetal-image-engine/src/add-mask.cpp +30 -15
  51. package/rosepetal-image-engine/src/add-masks.cpp +145 -102
  52. package/rosepetal-image-engine/src/advanced-mosaic.cpp +200 -129
  53. package/rosepetal-image-engine/src/blend.cpp +34 -20
  54. package/rosepetal-image-engine/src/codec.cpp +157 -0
  55. package/rosepetal-image-engine/src/color-convert.cpp +22 -19
  56. package/rosepetal-image-engine/src/concat.cpp +38 -43
  57. package/rosepetal-image-engine/src/crop.cpp +23 -26
  58. package/rosepetal-image-engine/src/draw.cpp +33 -10
  59. package/rosepetal-image-engine/src/filter.cpp +22 -26
  60. package/rosepetal-image-engine/src/heat-diff.cpp +35 -8
  61. package/rosepetal-image-engine/src/image-align.cpp +107 -35
  62. package/rosepetal-image-engine/src/main.cpp +4 -0
  63. package/rosepetal-image-engine/src/mosaic.cpp +31 -40
  64. package/rosepetal-image-engine/src/padding.cpp +30 -29
  65. package/rosepetal-image-engine/src/resize.cpp +20 -25
  66. package/rosepetal-image-engine/src/rotate.cpp +22 -23
  67. package/rosepetal-image-engine/src/utils.h +243 -144
  68. package/scripts/build-opencv-static.sh +6 -0
  69. package/scripts/dual-register.js +32 -25
  70. package/scripts/sync-version.js +58 -41
@@ -1,426 +1,164 @@
1
- # Image-Align Node (Ultra-Fast Image Alignment)
1
+ ---
2
+ title: "Image-Align Node - Align an Image to a Reference"
3
+ description: "Align a target image to a reference image in Node-RED with ECC, with ORB or SIFT features, or with features refined by ECC. Part of @rosepetal/node-red-contrib-image-tools."
4
+ head:
5
+ - - meta
6
+ - name: "keywords"
7
+ content: "node-red, image alignment, image registration, ecc, orb, sift, homography, opencv, rosepetal"
8
+ - - meta
9
+ - property: "og:title"
10
+ content: "Image-Align Node - @rosepetal/node-red-contrib-image-tools"
11
+ - - meta
12
+ - property: "og:description"
13
+ content: "Align a target image to a reference image in Node-RED with ECC, with ORB or SIFT features, or with features refined by ECC."
14
+ ---
15
+
16
+ # Image-Align Node
2
17
 
3
18
  ## Purpose & Use Cases
4
19
 
5
- The `image-align` node provides ultra-fast image alignment using OpenCV's Enhanced Correlation Coefficient (ECC) algorithm. It aligns a target image to match the position and orientation of a reference image, correcting for translation shifts and minor rotations. This is essential for computer vision workflows requiring precise image registration.
20
+ The `image-align` node moves a target image so that it lines up with a reference image, and returns it in the frame and size of the reference. It finds the transform with ORB or SIFT feature matching, with OpenCV's Enhanced Correlation Coefficient (ECC) algorithm, or with features refined by ECC, for a translation, euclidean, affine or homography motion model. It can also return the transform and move polygons with the image.
6
21
 
7
22
  **Real-World Applications:**
8
- - **Medical Imaging**: Align sequential scans or multi-modal medical images for comparison
9
- - **Quality Control**: Register product images for defect detection and comparison analysis
10
- - **Surveillance Systems**: Align camera feeds for motion detection and background subtraction
11
- - **Scientific Imaging**: Register microscopy images, satellite imagery, or astronomical photos
12
- - **Document Processing**: Align scanned documents for OCR and content analysis
13
- - **Augmented Reality**: Register camera feeds with reference markers for AR overlay
14
- - **Time-Lapse Photography**: Stabilize sequences by aligning frames to eliminate camera shake
15
-
16
- *[PLACEHOLDER - Add GIF showing before/after alignment of two shifted images]*
23
+ - **Quality Control**: Line up each product image with a golden image before comparing them (for example with [heat-diff](./heat-diff.md))
24
+ - **Region Mapping**: Move polygons found on the target image (for example a detection) to their place on the aligned image
25
+ - **Camera Shake**: Compensate small movements of a fixed camera between captures
26
+ - **Document Processing**: Bring scans of the same form into one frame
17
27
 
18
28
  ## Input/Output Specification
19
29
 
20
30
  ### Inputs
21
- The node expects a message containing two images at configurable paths:
22
- - **Reference Image**: The target image to align to (template)
23
- - **Target Image**: The image to be aligned (moved to match reference)
31
+ Only `msg` properties are read and written: the editor also offers `flow` and `global`, but the node reads the typed text as a `msg` path.
24
32
 
25
- ### Input Format
26
- Both images should follow the standard image object format:
27
- ```javascript
28
- {
29
- data: Buffer, // Raw pixel data
30
- width: number, // Image width in pixels
31
- height: number, // Image height in pixels
32
- channels: number, // Channel count (1, 3, 4)
33
- colorSpace: string, // "GRAY", "RGB", "RGBA", "BGR", "BGRA"
34
- dtype: string // "uint8" (standard)
35
- }
36
- ```
33
+ - **Reference Image** (`msg.payload.reference` by default): the image to align to
34
+ - **Target Image** (`msg.payload.target` by default): the image to move
35
+ - Each is a raw image object or an encoded JPEG/PNG/WebP/BMP `Buffer`. Both may also be arrays of the same length: the images are then paired by index and aligned in parallel; **Output to**, `transformMatrix` and the transformed polygons become arrays in the same order, while the other fields of `msg.alignment` stay single values.
36
+ - **Polygon Path** (`msg.payload.polygon` by default, with **Transform polygon coordinates**): one polygon `[[x, y], ...]` or an array of polygons `[[[x, y], ...], ...]`, normalized 0-1, giving positions on the target image
37
37
 
38
38
  ### Outputs
39
+ One output:
40
+ - **Output to** (`msg.payload` by default): the aligned target, with the width and height of the reference, as a raw image object or an encoded `Buffer` (JPEG/PNG/WebP). The area the target does not cover is black. When the alignment fails, the target is only scaled to the size of the reference.
41
+ - `msg.alignment`:
42
+
39
43
  ```javascript
40
44
  {
41
- payload: ImageObject, // Aligned image (target aligned to reference)
42
- alignment: {
43
- success: boolean, // Whether alignment succeeded
44
- timing: {
45
- convertMs: number, // Image conversion time
46
- taskMs: number, // Alignment processing time
47
- encodeMs: number // Output encoding time (if not raw)
48
- },
49
- preset: string, // Alignment preset used
50
- transformMatrix: { // Optional: only when returnMatrix enabled
51
- dx: number, // Horizontal translation in pixels
52
- dy: number, // Vertical translation in pixels
53
- matrix2x3: [ // OpenCV 2x3 affine matrix format
54
- a, b, dx, // [a b dx]
55
- c, d, dy // [c d dy] where typically a=d=1, b=c=0 for translation
56
- ],
57
- matrix3x3: [ // Standard 3x3 homogeneous transformation matrix
58
- a, b, dx, // [a b dx]
59
- c, d, dy, // [c d dy]
60
- 0, 0, 1 // [0 0 1 ] (homogeneous coordinates)
61
- ],
62
- transform: [] // Alias for matrix3x3 (backward compatibility)
63
- }
64
- }
45
+ success: true, // false when no transform was found (for arrays: true only if every pair succeeded)
46
+ timing: { convertMs, taskMs, encodeMs },
47
+ preset: "ultra-fast",
48
+ motionModel: "affine",
49
+ pipeline: "features+ecc",
50
+ eccRefine: "always",
51
+ detector: "orb",
52
+ transformMatrix: { // with "Return transformation matrix", when the alignment succeeded
53
+ dx: 12.4, dy: -3.1, // translation part, in pixels
54
+ matrix2x3: [a, b, dx, c, d, dy],
55
+ matrix3x3: [a, b, dx, c, d, dy, g, h, 1], // last row 0, 0, 1 except for homography
56
+ transform: [ ... ], // same as matrix3x3
57
+ motionModel: "affine", pipeline: "features+ecc", eccRefine: "always"
58
+ },
59
+ originalPolygon: [[0.1, 0.1], ...], // with "Transform polygon coordinates"
60
+ transformedPolygon: [[0.12, 0.09], ...], // or transformedPolygons for an array of polygons
61
+ isPolygonArray: false
65
62
  }
66
63
  ```
67
64
 
68
- ## Configuration Options
65
+ The matrix maps a pixel of the aligned (reference) frame to its position in the target image. The transformed polygons are the input polygons moved to where they lie on the aligned image, clamped to 0-1; they are only present when the alignment succeeded.
69
66
 
70
- ### Input Configuration
71
- - **Reference Image Path**: Location of reference image (default: `payload.reference`)
72
- - **Target Image Path**: Location of target image (default: `payload.target`)
73
- - **Path Sources**: Support for `msg.*`, `flow.*`, `global.*` contexts
74
-
75
- ### Output Configuration
76
- - **Output Path**: Where to store aligned image (default: `payload`)
77
- - **Output Format**: Raw, JPEG, PNG, or WebP
78
- - **Output Quality**: Compression quality for JPEG/WebP (1-100, default: 90)
79
- - **PNG Optimization**: Enable PNG compression optimization
80
-
81
- ### Alignment Settings
82
-
83
- #### Speed Presets
84
- The node offers four carefully tuned presets balancing speed and accuracy:
85
-
86
- **Ultra-Fast (Default)**
87
- - **Scale**: 0.2 (20% resolution for alignment calculation)
88
- - **Max Iterations**: 10
89
- - **Termination Epsilon**: 1e-1
90
- - **Use Case**: Real-time processing, minor alignment corrections
91
- - **Processing Time**: ~5-15ms per image pair
92
-
93
- **Fast**
94
- - **Scale**: 0.3 (30% resolution)
95
- - **Max Iterations**: 20
96
- - **Termination Epsilon**: 1e-2
97
- - **Use Case**: Batch processing with moderate accuracy needs
98
- - **Processing Time**: ~10-25ms per image pair
99
-
100
- **Balanced**
101
- - **Scale**: 0.5 (50% resolution)
102
- - **Max Iterations**: 30
103
- - **Termination Epsilon**: 1e-3
104
- - **Use Case**: General purpose alignment with good accuracy
105
- - **Processing Time**: ~20-50ms per image pair
106
-
107
- **Quality**
108
- - **Scale**: 0.7 (70% resolution)
109
- - **Max Iterations**: 50
110
- - **Termination Epsilon**: 1e-4
111
- - **Use Case**: High precision alignment for critical applications
112
- - **Processing Time**: ~40-100ms per image pair
113
-
114
- **Custom**
115
- - **Scale**: User-defined (0.1-1.0) - Image downscale factor for alignment calculation
116
- - **Max Iterations**: User-defined (1-200) - Maximum number of ECC iterations
117
- - **Termination Epsilon**: User-defined (0.000001-0.1) - Convergence threshold
118
- - **Use Case**: Fine-tuned performance for specific image types or requirements
119
- - **Processing Time**: Depends on parameters chosen
120
-
121
- ### Advanced Options
122
- - **Return Matrix**: Enable transformation matrix output for analysis
123
- - **Debug Mode**: Enable image preview display for development
124
- - **Debug Width**: Preview image width (default: 200 pixels)
125
-
126
- ## Algorithm Details
127
-
128
- ### Enhanced Correlation Coefficient (ECC)
129
- The node uses OpenCV's `findTransformECC()` with translation-only motion model for optimal speed:
130
-
131
- 1. **Preprocessing**: Convert both images to grayscale for alignment calculation
132
- 2. **Downsampling**: Scale images by preset factor for faster processing
133
- 3. **ECC Registration**: Find optimal translation transformation using iterative ECC algorithm
134
- 4. **Upscaling**: Scale transformation matrix back to full resolution
135
- 5. **Application**: Apply transformation to original color target image
136
- 6. **Output**: Return aligned target image matching reference position
137
-
138
- ### Motion Model
139
- - **Translation Only**: Corrects for X/Y shifts (most common alignment need)
140
- - **Benefits**: Faster processing, more stable than full affine transformation
141
- - **Limitations**: Cannot correct rotation, scaling, or perspective distortion
142
-
143
- ### Performance Optimizations
144
- - **Multi-threaded**: Leverages OpenCV's parallel processing capabilities
145
- - **Memory Efficient**: Processes images in-place where possible
146
- - **Adaptive Scaling**: Automatic resolution reduction for speed without quality loss
147
- - **Early Termination**: Stops iteration when convergence criteria met
67
+ - `msg.performance.rpimage.<key>`: `{ conversion, task, total }` in milliseconds
148
68
 
149
- ## Performance Notes
69
+ ## Configuration Options
150
70
 
151
- ### C++ Backend Processing
152
- - **OpenCV ECC**: Professional-grade image registration algorithm
153
- - **Async Processing**: Non-blocking execution with timing metrics
154
- - **Memory Management**: Efficient buffer handling between JS/C++ layers
155
- - **Error Recovery**: Graceful fallback if alignment fails
71
+ | Property | Default | Meaning |
72
+ |----------|---------|---------|
73
+ | Name | empty | Label of the node; also the key of its timings in `msg.performance.rpimage` |
74
+ | Reference Image | `msg.payload.reference` | Image to align to |
75
+ | Target Image | `msg.payload.target` | Image to move |
76
+ | Output to | `msg.payload` | Where the aligned image is written |
77
+ | Output Format | Raw (fastest) | Raw (fastest), JPEG, PNG or WebP, with Quality (`90`), PNG Optimize and the WebP options as in [resize](../transform/resize.md#output-format-options) |
78
+ | Debug / Debug Width | off / `200` | **Show aligned image**: a preview of the (first) aligned image under the node in the editor |
79
+ | Transform Matrix | off | **Return transformation matrix** in `msg.alignment.transformMatrix` |
80
+ | Transform Polygon | off | **Transform polygon coordinates** read from Polygon Path |
81
+ | Polygon Path | `msg.payload.polygon` | The polygon(s) to move |
82
+ | Pipeline | Features → ECC refine | **ECC only (intensity)**, **Features only (ORB)** (uses the selected Detector), **Features → ECC refine** or **Shift search (translation)** |
83
+ | Detector | ORB (fast, default) | **ORB** or **SIFT (robust, slower)**, for the feature stage |
84
+ | ECC Refine | Always (legacy, accurate) | With Features → ECC refine: **Always**, **Auto (skip when seed is strong)** or **Never (use seed only)** |
85
+ | Motion Model | Affine (6 DoF, +scale+shear) | **Translation (2 DoF)**, **Euclidean (3 DoF, +rotation)**, **Affine (6 DoF, +scale+shear)** or **Homography (8 DoF, +perspective)** |
86
+ | Speed Preset | Ultra Fast | Ultra Fast, Fast, Balanced, Quality or Custom: see below |
87
+ | Scale / Max Iterations / Termination Eps | `0.2` / `10` / `0.1` | *Custom only.* Number, or read from `msg`, `flow` or `global` |
88
+
89
+ Nodes saved by versions that had no Motion Model or Pipeline setting run as **Translation** with **ECC only**.
90
+
91
+ ### Pipelines
92
+ - **ECC only**: intensity-based ECC starting from no movement. Suits small shifts between images of the same scene.
93
+ - **Features only**: up to 800 ORB (or SIFT) keypoints per image, matched and fitted robustly (USAC MAGSAC for affine and homography, RANSAC for translation and euclidean). Handles larger movements; no ECC.
94
+ - **Features → ECC refine**: the feature result is the starting point of ECC. If ECC does not converge, the feature result is used. With **Auto**, ECC is skipped when the feature fit has at least 50 inliers; with **Never**, the feature result is used without ECC. When the feature stage finds no transform, ECC runs from no movement whatever ECC Refine says, so **Never** then differs from Features only, which fails.
95
+ - **Shift search**: tries every shift in a window and keeps the best, so it does not depend on keypoints. The centre of the target slides over the reference within ±10 % of the height and ±4 % of the width (at least 150 and 60 px at full resolution), on copies with each column mean and each line mean removed and slow shading high-passed: line-scan cameras add a column pattern that is identical in both images, and lamp flicker changes line brightness from one capture to the next. The peak is refined to sub-pixel. The result is always a pure translation, whatever Motion Model says. It fails (no transform) when the best normalized correlation is below 0.15 or sits on the edge of the window, where the true shift may lie outside it. Use it for low-texture images or wood grain, where keypoints are scarce or all alike along one direction. Max Iterations and Termination Eps are not used.
96
+
97
+ Before ECC, both images are converted to grayscale and their brightness and contrast are normalized, so moderate lighting changes are tolerated. ECC counts as converged when its correlation is above 0.1.
98
+
99
+ ### Speed Presets
100
+ Both stages work on copies of the images scaled by **Scale**; the transform is then scaled back to full resolution.
101
+
102
+ | Preset | Scale | Max Iterations | Termination Eps |
103
+ |--------|-------|----------------|-----------------|
104
+ | Ultra Fast | 0.2 | 10 | 0.1 |
105
+ | Fast | 0.3 | 20 | 0.01 |
106
+ | Balanced | 0.5 | 30 | 0.001 |
107
+ | Quality | 0.7 | 50 | 0.0001 |
108
+ | Custom | 0.1 to 1.0 | 1 to 200 | 0.000001 to 0.1 |
109
+
110
+ Max Iterations and Termination Eps apply to ECC. Custom values outside the ranges are clamped; empty or `0` values fall back to 0.2, 10 and 0.1, and a value that is not a number is an error (`... is not a valid number.`).
111
+
112
+ ### Image Sizes
113
+ For the ECC pipelines, and whenever polygons are transformed, a target of another size is first scaled to the size of the reference. With Features only, the target keeps its size for matching. The aligned image is resampled with nearest-neighbour interpolation.
114
+
115
+ ## Status and Errors
116
+
117
+ - **Success**: green dot `OK: <n> img in <t> ms (conv <c> ms | task <k> ms)`, where `<n>` is the number of pairs, plus the preview format with Debug on. A failed alignment is not an error: check `msg.alignment.success`
118
+ - **Failure**: `msg.error` is set, the target image (the first one of an array) is written to **Output to**, a warning is logged, the status shows a red ring `Error: <first 30 characters>` and the message is still sent. Messages include `Reference and target must both be single images or both be arrays`, `Image arrays must be non-empty and of equal length (got <a> and <b>)`, `Reference image is invalid or missing` and `Target image is invalid or missing`
119
+ - **Invalid polygons**: a warning such as `Invalid coordinate at index 2: coordinates must be in range [0, 1]`, and the polygon transform is skipped
156
120
 
157
- ### Speed Characteristics
158
- - **Ultra-Fast Preset**: 5-15ms processing time, suitable for real-time workflows
159
- - **Quality Preset**: 40-100ms processing time for precision alignment
160
- - **Batch Processing**: Parallel execution support for multiple image pairs
161
- - **Scalability**: Linear performance scaling with image resolution
121
+ ## Performance Notes
162
122
 
163
- ### Memory Usage
164
- - **Temporary Buffers**: ~2-3x source image memory during processing
165
- - **Optimization**: Automatic cleanup after processing completion
166
- - **Large Images**: Consider downsampling very large images for speed
123
+ - Alignment and encoding run in the native OpenCV addon on the libuv thread pool; pairs of an array are aligned in parallel
124
+ - Repeated inputs are cached in the addon (scaled grayscale images, prepared ECC images and feature results), which helps the common case of one fixed reference and a new target per message
125
+ - SIFT is slower than ORB; Homography is the most flexible model and the easiest to fit wrongly on images with few features
167
126
 
168
127
  ## Real-World Examples
169
128
 
170
- ### Medical Image Registration
129
+ ### Golden-Image Comparison
171
130
  ```
172
- [MRI Scan T1] + [MRI Scan T2] → [Image-Align: quality] → [Registered T2] → [Comparison Analysis]
131
+ [Function: msg.payload = { reference: golden, target: msg.capture }; msg.goldenImage = golden] → [Image-Align: Features → ECC, Affine, Balanced] → [Heat-Diff]
173
132
  ```
174
- Align multi-modal medical images for accurate comparison and analysis.
133
+ Align each capture to a golden image before computing the difference.
175
134
 
176
- ### Quality Control System
135
+ ### Region Follows the Image
177
136
  ```
178
- [Reference Product] + [Test Product] → [Image-Align: balanced] → [Aligned Test] → [Defect Detection]
137
+ [Function: set payload.reference, payload.target, payload.polygon] → [Image-Align: Transform polygon coordinates] → [Function: msg.roi = msg.alignment.transformedPolygon] → [Add-Mask: Image msg.payload, Polygon Path msg.roi]
179
138
  ```
180
- Register product images for precise defect detection and quality analysis.
139
+ A region found on the target before alignment is drawn in the right place on the aligned image.
181
140
 
182
- ### Surveillance Motion Detection
141
+ ### Batch of Stations
183
142
  ```
184
- [Background Reference] + [Current Frame] → [Image-Align: ultra-fast] → [Stabilized Frame] → [Motion Analysis]
185
- ```
186
- Stabilize camera feeds for accurate motion detection and tracking.
187
-
188
- ### Document Processing
189
- ```
190
- [Template Document] + [Scanned Document] → [Image-Align: fast] → [Registered Scan] → [OCR Processing]
191
- ```
192
- Align scanned documents with templates for improved OCR accuracy.
193
-
194
- ### Scientific Imaging
143
+ [Function: payload.reference = [ref1, ref2, ref3]; payload.target = [img1, img2, img3]] → [Image-Align] → [Split]
195
144
  ```
196
- [Reference Microscopy] + [Sample Image] → [Image-Align: quality] → [Registered Sample] → [Analysis Pipeline]
197
- ```
198
- Register scientific images for precise measurement and comparison.
145
+ Three camera stations aligned in one message, each to its own reference.
199
146
 
200
147
  ## Common Issues & Troubleshooting
201
148
 
202
- ### Alignment Failures
203
- - **Issue**: `alignment.success = false` in output
204
- - **Causes**: Images too different, poor lighting, insufficient features
205
- - **Solutions**: Try different preset, improve image quality, use more similar reference
149
+ ### Alignment Fails (`success: false`)
150
+ - **Cause**: too little texture or overlap, a movement too large for ECC only, or a motion model that cannot describe the movement
151
+ - **Solution**: use **Features → ECC refine**, try **SIFT** on blurry or low-texture images, raise the preset (Balanced or Quality), or pick a model with more freedom
206
152
 
207
- ### Poor Alignment Quality
208
- - **Issue**: Images appear misaligned despite success=true
209
- - **Causes**: Complex transformations beyond translation, low image contrast
210
- - **Solutions**: Use Quality preset, improve image preprocessing, verify motion model suitability
153
+ ### Wrong Alignment
154
+ - **Cause**: repeated patterns or a model with too much freedom (Homography on few features)
155
+ - **Solution**: use the simplest model that fits the setup (Translation or Euclidean for a fixed camera)
211
156
 
212
- ### Performance Issues
213
- - **Issue**: Slow processing times
214
- - **Causes**: Large images, complex patterns, high-quality presets
215
- - **Solutions**: Use Ultra-Fast preset, downsample large images, optimize image quality
216
-
217
- ### Memory Problems
218
- - **Issue**: Out of memory errors with large images
219
- - **Causes**: Very high resolution images, insufficient system memory
220
- - **Solutions**: Downsample images, process in batches, increase system memory
221
-
222
- ### Format Compatibility
223
- - **Issue**: Alignment fails with certain image formats
224
- - **Causes**: Unsupported color spaces, unusual bit depths
225
- - **Solutions**: Convert to standard formats, verify image structure
226
-
227
- ## Integration Patterns
228
-
229
- ### Computer Vision Pipeline
230
- ```
231
- Image Capture → Preprocessing → Image-Align → Feature Extraction → Analysis
232
- ```
233
- Standard computer vision workflow with image stabilization.
234
-
235
- ### Quality Inspection System
236
- ```
237
- Reference Capture → Product Capture → Image-Align → Difference Analysis → Pass/Fail
238
- ```
239
- Automated quality control with precise image registration.
240
-
241
- ### Medical Imaging Workflow
242
- ```
243
- Reference Scan → Patient Scan → Image-Align → Comparative Analysis → Diagnosis Support
244
- ```
245
- Medical image registration for diagnostic comparison.
246
-
247
- ### Document Processing Pipeline
248
- ```
249
- Template Scan → Document Scan → Image-Align → OCR Processing → Content Extraction
250
- ```
251
- Document alignment for improved text recognition.
252
-
253
- ## Advanced Usage
254
-
255
- ### Dynamic Preset Selection
256
- ```javascript
257
- // In function node before image-align:
258
- // Choose preset based on image characteristics
259
- const imageSize = msg.payload.reference.width * msg.payload.reference.height;
260
- if (imageSize > 2000000) { // Large images
261
- msg.alignmentPreset = 'ultra-fast';
262
- } else if (msg.criticalAccuracy) {
263
- msg.alignmentPreset = 'quality';
264
- } else {
265
- msg.alignmentPreset = 'balanced';
266
- }
267
- ```
268
-
269
- ### Custom Parameters for Fine-Tuning
270
- ```javascript
271
- // Configure image-align node with custom preset for specific use case
272
- const nodeConfig = {
273
- preset: 'custom',
274
- customScale: 0.4, // Medium resolution for balance
275
- customMaxIterations: 25, // Moderate iterations
276
- customTerminationEps: 5e-3 // Balanced convergence threshold
277
- };
278
-
279
- // Example: High-precision alignment for microscopy images
280
- const microscopeConfig = {
281
- preset: 'custom',
282
- customScale: 0.8, // High resolution to capture fine details
283
- customMaxIterations: 75, // More iterations for precision
284
- customTerminationEps: 1e-5 // Very strict convergence
285
- };
286
-
287
- // Example: Ultra-fast alignment for video frames
288
- const videoConfig = {
289
- preset: 'custom',
290
- customScale: 0.15, // Very low resolution for speed
291
- customMaxIterations: 5, // Minimal iterations
292
- customTerminationEps: 0.05 // Loose convergence for speed
293
- };
294
- ```
295
-
296
- ### Batch Processing Pattern
297
- ```javascript
298
- // Process multiple image pairs with consistent reference
299
- msg.imageQueue.forEach((target, index) => {
300
- msg.payload = {
301
- reference: msg.referenceImage, // Consistent reference
302
- target: target // Different target for each
303
- };
304
- // Send to image-align node
305
- });
306
- ```
307
-
308
- ### Quality Validation
309
- ```javascript
310
- // After image-align node:
311
- if (msg.alignment.success && msg.alignment.timing.taskMs < 100) {
312
- // Alignment succeeded and was fast - good quality match
313
- msg.qualityScore = 'excellent';
314
- } else if (msg.alignment.success) {
315
- // Alignment succeeded but slow - challenging alignment
316
- msg.qualityScore = 'good';
317
- } else {
318
- // Alignment failed - images too different
319
- msg.qualityScore = 'poor';
320
- // Consider fallback processing
321
- }
322
- ```
323
-
324
- ### Performance Monitoring
325
- ```javascript
326
- // Track alignment performance over time
327
- if (!flow.get('alignmentStats')) {
328
- flow.set('alignmentStats', { total: 0, successful: 0, avgTime: 0 });
329
- }
330
-
331
- const stats = flow.get('alignmentStats');
332
- stats.total++;
333
- if (msg.alignment.success) {
334
- stats.successful++;
335
- }
336
- stats.avgTime = (stats.avgTime * (stats.total - 1) + msg.alignment.timing.taskMs) / stats.total;
337
- flow.set('alignmentStats', stats);
338
-
339
- msg.performanceStats = {
340
- successRate: stats.successful / stats.total,
341
- averageTime: stats.avgTime
342
- };
343
- ```
344
-
345
- ### Transformation Matrix Analysis
346
- ```javascript
347
- // After image-align node with returnMatrix enabled:
348
- if (msg.alignment.success && msg.alignment.transformMatrix) {
349
- const matrix = msg.alignment.transformMatrix;
350
-
351
- // Simple translation values
352
- node.log(`Image shifted by dx: ${matrix.dx}, dy: ${matrix.dy} pixels`);
353
-
354
- // Access different matrix formats
355
- const opencv2x3 = matrix.matrix2x3; // [a, b, dx, c, d, dy]
356
- const homogeneous3x3 = matrix.matrix3x3; // [a, b, dx, c, d, dy, 0, 0, 1]
357
- const transform = matrix.transform; // Same as matrix3x3
358
-
359
- // Analyze alignment quality
360
- const totalShift = Math.sqrt(matrix.dx * matrix.dx + matrix.dy * matrix.dy);
361
- if (totalShift < 5) {
362
- msg.alignmentQuality = 'excellent';
363
- } else if (totalShift < 20) {
364
- msg.alignmentQuality = 'good';
365
- } else {
366
- msg.alignmentQuality = 'poor';
367
- }
368
-
369
- // Store for applying to other images
370
- flow.set('lastAlignment', matrix);
371
- }
372
- ```
373
-
374
- ### Applying Transformation to Other Images
375
- ```javascript
376
- // Use stored transformation matrix to align additional images
377
- const storedMatrix = flow.get('lastAlignment');
378
- if (storedMatrix && msg.additionalImages) {
379
- msg.additionalImages.forEach((image, index) => {
380
- // Note: You would need a custom transformation function or another alignment node
381
- // The matrix provides the exact translation values needed
382
- msg.transformationNeeded = {
383
- dx: storedMatrix.dx,
384
- dy: storedMatrix.dy
385
- };
386
- });
387
- }
388
- ```
157
+ ### Black Borders
158
+ - **Issue**: Edges of the output are black
159
+ - **Cause**: Those areas of the reference frame are not covered by the moved target
160
+ - **Solution**: Crop the output, or ignore the border in later comparisons
389
161
 
390
- ## Best Practices
391
-
392
- ### Image Preparation
393
- - Use images with sufficient contrast and distinctive features
394
- - Ensure reasonable similarity between reference and target images
395
- - Consider preprocessing (histogram equalization, noise reduction) for challenging images
396
- - Maintain consistent lighting conditions when possible
397
-
398
- ### Performance Optimization
399
- - Start with Ultra-Fast preset and upgrade only if accuracy insufficient
400
- - Downsample very large images (>4MP) before alignment if possible
401
- - Use Raw output format for processing chains to avoid encoding overhead
402
- - Monitor timing metrics to optimize preset selection
403
-
404
- ### Quality Control
405
- - Always check `alignment.success` flag before using results
406
- - Implement fallback behavior for alignment failures
407
- - Monitor processing times to detect performance degradation
408
- - Validate alignment quality using automated metrics when possible
409
-
410
- ### Error Handling
411
- - Implement graceful handling of alignment failures
412
- - Provide meaningful feedback for different failure modes
413
- - Log alignment statistics for system monitoring
414
- - Consider retry logic with different presets for critical applications
415
-
416
- ### Integration Strategy
417
- - Design workflows to handle both successful and failed alignments
418
- - Implement quality scoring based on timing and success metrics
419
- - Consider batch processing patterns for efficiency with multiple images
420
- - Plan for scalability based on expected image volumes and quality requirements
421
-
422
- ### Debug and Development
423
- - Enable debug mode during development for visual verification
424
- - Use timing metrics to optimize preset selection for your use case
425
- - Test with representative image pairs from your target domain
426
- - Validate alignment quality using domain-specific metrics
162
+ ### Images from Context Are Ignored
163
+ - **Issue**: Reference or target set to `flow` or `global` is not found
164
+ - **Solution**: Copy the images into the message first; this node reads `msg` properties only
@@ -0,0 +1,101 @@
1
+ ---
2
+ title: "Color-Convert Node - Convert Between Color Spaces"
3
+ description: "Convert images in Node-RED between the GRAY, RGB, RGBA, BGR and BGRA color spaces, one image or an array. Part of @rosepetal/node-red-contrib-image-tools."
4
+ head:
5
+ - - meta
6
+ - name: "keywords"
7
+ content: "node-red, color-convert, color space, grayscale, rgb, bgr, rgba, alpha channel, opencv, rosepetal"
8
+ - - meta
9
+ - property: "og:title"
10
+ content: "Color-Convert Node - @rosepetal/node-red-contrib-image-tools"
11
+ - - meta
12
+ - property: "og:description"
13
+ content: "Convert images in Node-RED between the GRAY, RGB, RGBA, BGR and BGRA color spaces, one image or an array."
14
+ ---
15
+
16
+ # Color-Convert Node
17
+
18
+ > **Type**: `rp-color-convert` · **Category**: Transform · **Since**: v1.2.2
19
+
20
+ ## Overview
21
+
22
+ Color-Convert converts an image, or every image of an array, to another color space: grayscale, RGB, RGBA, BGR or BGRA. The pixels are converted with OpenCV (`cv::cvtColor`) and the `colorSpace` and `channels` of the result change with them. The size of the image does not change.
23
+
24
+ **Use cases**
25
+ - Turn camera images into grayscale before a filter or a model that expects one channel
26
+ - Hand BGR images to a library that expects RGB, or the opposite
27
+ - Add an alpha channel before compositing, or drop it before saving as JPEG
28
+
29
+ ## Inputs
30
+
31
+ - **Input** (`msg.payload` by default; `msg`, `flow` or `global`): one image or an array of images. Each image is a raw image object (`colorSpace` `GRAY`, `RGB`, `RGBA`, `BGR` or `BGRA`) or an encoded JPEG/PNG/WebP/BMP `Buffer`, which the addon decodes as RGB, RGBA or GRAY. The images of an array are converted in parallel.
32
+
33
+ ## Outputs
34
+
35
+ One output.
36
+
37
+ - **Output** (`msg.payload` by default): the converted image, or an array in the input order. A raw image object with `colorSpace` set to the target and `channels` 1, 3 or 4; or an encoded `Buffer` when **Output Format** is JPEG, PNG or WebP.
38
+ - `msg.performance.rpimage.<key>`: `{ conversion, task, total }` in milliseconds.
39
+ - On failure: `msg.error` (`message`, `operation`, `hint`, `details`, `timestamp`, `nodeId`, `nodeName`, `nodeType`), with the input written back to **Output**; the message is still sent.
40
+
41
+ What each conversion does:
42
+
43
+ | From → To | Result |
44
+ |---|---|
45
+ | Same color space | The image unchanged |
46
+ | Color → GRAY | Luminance (weighted sum of R, G and B); the alpha channel is dropped |
47
+ | GRAY → color | The gray value copied to the three color channels; alpha, when added, is 255 |
48
+ | RGB ↔ BGR, RGBA ↔ BGRA | The red and blue channels swapped |
49
+ | 3 channels → 4 channels | An opaque alpha channel (255) added |
50
+ | 4 channels → 3 channels | The alpha channel dropped |
51
+
52
+ ## Configuration
53
+
54
+ | Field | Type | Default | Description |
55
+ |---|---|---|---|
56
+ | Name | string | empty | Label of the node; also the key of its timings in `msg.performance.rpimage` |
57
+ | Input | TypedInput (msg/flow/global) | `msg.payload` | Where the image or array is read |
58
+ | Output | TypedInput (msg/flow/global) | `msg.payload` | Where the result is written |
59
+ | Output Format | enum | Raw (fastest) | Raw (fastest), JPEG, PNG or WebP |
60
+ | Quality | number | `90` | JPEG and WebP quality, 1-100 |
61
+ | PNG Optimize | boolean | off | **Compress PNG (slower, smaller file)**: PNG compression level 6 instead of 0 |
62
+ | Lossless | boolean | off | WebP: **Encode WebP without loss** |
63
+ | Smart Subsample | boolean | off | WebP: **Better chroma downsampling (lossy only)** |
64
+ | Effort | number | empty | WebP: 0-6. When Lossless, Smart Subsample or Effort is set, the WebP is encoded with `sharp` instead of OpenCV |
65
+ | Debug | boolean | off | **Show processed image**: a preview under the node in the editor (the first image of an array) |
66
+ | Debug Width | TypedInput (num/msg/flow/global) | `200` | Width of the preview in pixels |
67
+ | Target Color Space | enum | RGB | Grayscale (GRAY), RGB, RGBA, BGR or BGRA |
68
+
69
+ The status shows a green dot `OK: <n> img in <t> ms (conv <c> ms | task <k> ms)` after a conversion, and a red ring `Error: <first 30 characters>` after a failure.
70
+
71
+ ## Examples
72
+
73
+ ```
74
+ [rp-image-in] → [rp-color-convert: GRAY] → [rp-filter: Otsu Threshold] → [rp-image-out]
75
+ ```
76
+
77
+ Converts a photo to one channel and binarizes it.
78
+
79
+ ```
80
+ [camera (BGR)] → [rp-color-convert: RGB] → [function: send to a service that expects RGB]
81
+ ```
82
+
83
+ Swaps the channel order of BGR camera images.
84
+
85
+ ```
86
+ [rp-image-in] → [rp-color-convert: RGBA] → [rp-blend: Alpha compositing]
87
+ ```
88
+
89
+ Adds an opaque alpha channel to an image before it is composited.
90
+
91
+ ## Troubleshooting
92
+
93
+ - **`Invalid image structure` in `msg.error`** — Cause: the `colorSpace` of the input does not match its channel count (for example `RGB` with 4 channels), or the data length does not match `width × height × channels`. · Solution: check the node that produced the image; the warning logged before the error names the problem.
94
+ - **`Unsupported color space conversion: <from> -> <to>`** — Cause: the input `colorSpace` is not one of the five names in upper case. · Solution: set `colorSpace` to `GRAY`, `RGB`, `RGBA`, `BGR` or `BGRA`.
95
+ - **Transparency lost** — Cause: converting to GRAY, RGB or BGR drops the alpha channel, and so does JPEG output. · Solution: target RGBA or BGRA and save as PNG or WebP.
96
+
97
+ ## See Also
98
+
99
+ - [filter](./filter.md): Otsu threshold, histogram equalization and other filters
100
+ - [padding](./padding.md): add margins, transparent on images with alpha
101
+ - [blend](../blend/blend.md): blend two images, with alpha compositing