@rosepetal/node-red-contrib-image-tools 1.7.0 → 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 (35) hide show
  1. package/.github/workflows/build-prebuild.yml +1 -1
  2. package/README.md +39 -21
  3. package/docs/index.md +156 -0
  4. package/docs/nodes/blend/add-bbs.md +116 -0
  5. package/docs/nodes/blend/add-mask.md +67 -224
  6. package/docs/nodes/blend/add-masks.md +74 -196
  7. package/docs/nodes/blend/blend.md +84 -200
  8. package/docs/nodes/io/folder-in.md +92 -0
  9. package/docs/nodes/io/image-in.md +61 -52
  10. package/docs/nodes/io/image-out.md +114 -93
  11. package/docs/nodes/mix/advanced-mosaic.md +124 -78
  12. package/docs/nodes/mix/concat.md +71 -56
  13. package/docs/nodes/mix/mosaic.md +81 -91
  14. package/docs/nodes/specialized/cropBB.md +76 -214
  15. package/docs/nodes/specialized/heat-diff.md +111 -0
  16. package/docs/nodes/specialized/image-align.md +125 -387
  17. package/docs/nodes/transform/color-convert.md +101 -0
  18. package/docs/nodes/transform/crop.md +56 -58
  19. package/docs/nodes/transform/draw.md +46 -26
  20. package/docs/nodes/transform/filter.md +110 -46
  21. package/docs/nodes/transform/padding.md +55 -55
  22. package/docs/nodes/transform/resize.md +81 -56
  23. package/docs/nodes/transform/rotate.md +67 -50
  24. package/node-red-contrib-image-tools/nodes/specialized/image-align.html +11 -4
  25. package/node-red-contrib-image-tools/nodes/specialized/image-align.js +2 -1
  26. package/npm/darwin-arm64/package.json +1 -1
  27. package/npm/darwin-x64/package.json +1 -1
  28. package/npm/linux-arm64/package.json +1 -1
  29. package/npm/linux-x64/package.json +1 -1
  30. package/npm/linuxmusl-x64/package.json +1 -1
  31. package/npm/win32-x64/package.json +1 -1
  32. package/package.json +6 -6
  33. package/rosepetal-image-engine/src/heat-diff.cpp +4 -0
  34. package/rosepetal-image-engine/src/image-align.cpp +71 -3
  35. package/scripts/build-opencv-static.sh +6 -0
@@ -1,8 +1,23 @@
1
+ ---
2
+ title: "Image-Out Node - Save Images to Disk"
3
+ description: "Save raw images or encoded buffers to disk as JPEG, PNG, WebP or BMP in Node-RED, with timestamped file names and overwrite protection. Part of @rosepetal/node-red-contrib-image-tools."
4
+ head:
5
+ - - meta
6
+ - name: "keywords"
7
+ content: "node-red, image-out, save image, write image file, jpeg, png, webp, bmp, timestamp, rosepetal"
8
+ - - meta
9
+ - property: "og:title"
10
+ content: "Image-Out Node - @rosepetal/node-red-contrib-image-tools"
11
+ - - meta
12
+ - property: "og:description"
13
+ content: "Save raw images or encoded buffers to disk as JPEG, PNG, WebP or BMP in Node-RED, with timestamped file names and overwrite protection."
14
+ ---
15
+
1
16
  # Image-Out Node
2
17
 
3
18
  ## Purpose & Use Cases
4
19
 
5
- The `image-out` node is the primary output point for saving processed images to the filesystem from Node-RED flows. It features automatic timestamp-based naming, overwrite protection, and flexible format conversion, making it ideal for production workflows.
20
+ The `image-out` node is the primary output point for saving processed images to the filesystem from Node-RED flows. It names files with a timestamp or a name you give, protects existing files from being overwritten, converts between formats, and can cap the number of files in the folder and stop saving when the disk is nearly full.
6
21
 
7
22
  **Real-World Applications:**
8
23
  - **Automated Image Processing**: Save processed images with organized timestamp naming
@@ -14,98 +29,95 @@ The `image-out` node is the primary output point for saving processed images to
14
29
  ## Input/Output Specification
15
30
 
16
31
  ### Inputs
17
- The node accepts either:
18
- - **Raw Image Object**: Standard format with `data`, `width`, `height`, `channels`, `colorSpace`
19
- - **Encoded Buffer**: JPEG, PNG, or WebP buffer (automatically detected and handled). Note: BMP output is not supported from encoded buffers — use raw image objects instead.
32
+ In **Single image** mode, the image read from **Input from** (`msg.payload` by default) is either:
33
+ - **Raw Image Object**: `data`, `width`, `height`, `channels`, `colorSpace` (as produced by the other nodes)
34
+ - **Encoded Buffer**: a JPEG, PNG or WebP file in a `Buffer`. A buffer already in the output format is written as it is; otherwise `sharp` converts it. BMP output needs a raw image object.
35
+
36
+ One image per message: an array is not accepted in this mode. To save several images from one message, use **Multiple images** mode.
37
+
38
+ In **Multiple images** mode, **Input** (`msg.payload` by default) is an array of objects (a single object is treated as an array of one). Each object carries its image in **Image field** (`bitmap` by default), its folder (`outputDir`; an item without one is skipped unless **Output dir** sets one folder for all items) and optionally its file name:
39
+
40
+ ```javascript
41
+ msg.payload = [
42
+ { bitmap: <image>, outputDir: "/data/ok", filename: "part_0001.png" },
43
+ { bitmap: <image>, outputDir: "/data/nok" } // no filename: image_<timestamp>.<format>
44
+ ];
45
+ ```
20
46
 
21
47
  ### Outputs
22
- This is a terminal node with no outputs. It saves images to the filesystem and displays status information.
48
+ None. The node writes files and reports the result in its status.
23
49
 
24
50
  ### Button Control
25
- - **Right-side button**: Toggle node active/inactive state (similar to debug node)
26
- - **Green**: Active and saving images
27
- - **Gray**: Inactive (passes through without saving)
51
+ - **Button on the node**: switches the deployed node between active and inactive at once, like the button of the Debug node. The flow is marked as changed, so the state is saved with the next deploy.
52
+ - **Inactive**: grey dot `inactive`; incoming messages are dropped without saving.
28
53
 
29
54
  ## Configuration Options
30
55
 
31
- ### Folder Path
32
- - **Type**: String | msg | flow | global (required)
33
- - **Description**: Directory where images will be saved
34
- - **Options**:
35
- - **String**: Static path (e.g., `/home/user/output/`)
36
- - **msg.***: Dynamic path from message (e.g., `msg.folder`)
37
- - **flow.***: Path from flow context
38
- - **global.***: Path from global context
39
- - **Auto-creation**: Directory is created if it doesn't exist
40
-
41
- ### Filename Prefix
42
- - **Type**: String (optional)
43
- - **Default**: "image"
44
- - **Description**: Custom prefix for generated filenames
45
- - **Pattern**: `[prefix]_YYYYMMDD_HHMMSS.[ext]`
46
- - **Example**: With prefix "webcam" → `webcam_20240109_143022.jpg`
47
-
48
- ### Input From
49
- - **Default**: `msg.payload`
50
- - **Options**: Any message property, flow, or global variable
51
- - **Accepts**: Both raw image objects and encoded buffers
52
-
53
- ### Output Format
54
- - **Options**: JPEG, PNG, WebP, BMP
55
- - **Description**: Target format for saved images
56
- - **Conversion**: Automatic conversion if input format differs
57
- - **BMP**: Uncompressed format with no quality/compression settings. Requires raw image data input.
58
-
59
- ### Quality
60
- - **Type**: Number (1-100)
61
- - **Default**: 90
62
- - **Applies to**: JPEG and WebP formats
63
- - **Description**: Higher values = better quality but larger files
64
-
65
- ### PNG Optimize
66
- - **Type**: Boolean
67
- - **Default**: false
68
- - **Description**: Maximum compression for PNG files (slower but smaller)
56
+ | Property | Default | Meaning |
57
+ |----------|---------|---------|
58
+ | Name | empty | Label of the node in the editor |
59
+ | Mode | Single image | **Single image**: one image per message. **Multiple images**: an array of items, each with its own image, folder and file name |
60
+ | Folder Path | empty | *Single image.* Folder where the file is written: a string, or read from `msg`, `flow` or `global`. An empty string saves to the working directory of the Node-RED process |
61
+ | Filename Prefix | empty | *Single image.* Prefix of the generated name (`<prefix>_<timestamp>`). Empty: `image`. String, `msg`, `flow`, `global` or JSONata |
62
+ | Full Filename | empty | *Single image.* A complete file name that replaces the generated one. String, `msg`, `flow`, `global` or JSONata |
63
+ | Input from | `msg.payload` | *Single image.* Where the image is read: a `msg` property or a `flow` / `global` key |
64
+ | Input | `msg.payload` | *Multiple images.* Where the array of items is read |
65
+ | Image field | `bitmap` | *Multiple images.* Property of each item that holds the image |
66
+ | Output dir | item field `outputDir` | *Multiple images.* Folder of each item: a property of the item, or one folder for all items (string, `msg`, `flow` or `global`) |
67
+ | Filename | item field `filename` | *Multiple images.* File name of each item: a property of the item, or one name for all items (string, `msg`, `flow` or `global`) |
68
+ | Output Format | JPEG | JPEG, PNG, WebP or BMP |
69
+ | Quality | `90` | 1-100, for JPEG and WebP |
70
+ | Compression | `8` | PNG compression level, 0-9 (higher: smaller file, slower) |
71
+ | WebP Lossless | off | Encode WebP without loss |
72
+ | WebP Smart Subsample | off | Better chroma downsampling, lossy WebP only |
73
+ | WebP Effort | `0` | 0-6, higher gives a smaller file and is slower. Empty leaves the `sharp` default |
74
+ | Protection | on | Prevent overwriting existing files: a name that is taken gets `_2`, `_3` and so on |
75
+ | Max Images | empty | Keep at most this many files in the folder, deleting the oldest. Empty or `0` keeps all. Number, `msg`, `flow` or `global` |
76
+ | Disk Limit | `95` | Skip saving when the disk of the folder is at least this % full. `0` disables the check |
77
+ | Debug | off | *Single image.* **Show saved image preview** under the node in the editor |
78
+ | Debug Width | `200` | Width of the preview in pixels (a number; values read from `msg`, `flow` or `global` are not resolved by this node and give 200) |
79
+
80
+ ### File Names
81
+ - **Generated name**: `<prefix>_<timestamp>.<ext>`, with the prefix `image` when **Filename Prefix** is empty. The timestamp is the UTC time with milliseconds, `YYYYMMDD_HHMMSS-mmmZ`: for example `image_20240109_143022-517Z.jpg`.
82
+ - **Full Filename** / **Filename**: used as given. If it ends in `.jpg`, `.jpeg`, `.png`, `.webp` or `.bmp`, that extension sets the format of this file instead of **Output Format**. Without an extension, the extension of **Output Format** is added. A name with `/` or `\` is rejected. Another extension is an error in Single image mode (`Unsupported extension in filename: .tif`); in Multiple images mode it is replaced by the extension of **Output Format**.
83
+ - In Multiple images mode an item without a file name gets `image_<timestamp>.<ext>`; **Filename Prefix** does not apply.
84
+ - Folders are created when they do not exist.
69
85
 
70
86
  ### Overwrite Protection
71
- - **Type**: Boolean
72
- - **Default**: true
73
- - **Description**: Automatically appends `_2`, `_3`, etc. to prevent overwriting
74
- - **Example**: If `image_20240109_143022.jpg` exists, saves as `image_20240109_143022_2.jpg`
87
+ With **Protection** checked, a name that already exists in the folder becomes `<name>_2.<ext>`, then `_3` and so on, up to `_999`. The node knows the files of a folder from one listing made when it first writes there, plus its own writes; files that other programs create later are seen again only when **Max Images** re-lists the folder (at most every 5 seconds).
75
88
 
76
- ### Debug Preview
77
- - **Type**: Boolean
78
- - **Default**: false
79
- - **Description**: Shows saved image preview on the node
89
+ ### Max Images
90
+ After each save the node counts **every file in the folder**, not only the images it wrote, and deletes the oldest ones (by modification time) until at most **Max Images** remain. Use a folder of its own for each Image-Out node that has a limit.
80
91
 
81
- ## Performance & Technical Details
92
+ ### Disk Limit
93
+ Before writing, the node reads the usage of the file system of the folder. At or above the limit it logs a warning, shows a yellow `disk <n>% full` status and skips the file (in Multiple images mode, the remaining items of the message; when no item of the message was saved, the node then fails with `All <n> items failed.`).
82
94
 
83
- ### Timestamp Naming
84
- Files are automatically named with timestamps:
85
- - **Format**: `YYYYMMDD_HHMMSS`
86
- - **Example**: `image_20240109_143022.jpg`
87
- - **Benefits**: Chronological ordering, no conflicts, easy sorting
95
+ ## Performance & Technical Details
88
96
 
89
97
  ### Format Handling
90
- The node intelligently handles format conversions:
91
- - **Same Format**: Direct save without re-encoding (fastest)
92
- - **Different Format**: Automatic conversion using Sharp
93
- - **Raw to Encoded**: Full processing with color space handling
94
- - **Encoded to Encoded**: Smart re-encoding only when needed
98
+ - **Raw image to JPEG, PNG or WebP**: encoded with `sharp`. BGR and BGRA images are converted to RGB/RGBA by the native addon first.
99
+ - **Raw image to BMP**: encoded by the native OpenCV addon (uncompressed; 8-bit grayscale, 24-bit or 32-bit).
100
+ - **Encoded buffer in the output format**: written without re-encoding. A WebP buffer is re-encoded when **WebP Lossless** or **WebP Effort** is set.
101
+ - **Encoded buffer in another format**: converted with `sharp`.
95
102
 
96
103
  ### Status Indicators
97
- - **Gray dot "inactive"**: Node disabled via button
98
- - **Blue dot "saving..."**: Currently writing to disk
99
- - **Green dot "saved: filename.jpg"**: Success with filename
100
- - **Red dot "Error"**: Save failed (check debug panel)
104
+ - **Grey dot** `inactive`: the node is switched off with its button
105
+ - **Blue dot** `saving...`: writing to disk
106
+ - **Green dot** `saved: <file> (<ms>ms)`, or `saved: <file> (<ms>ms, avoided overwrite)` when the name got a suffix. With Debug: `saved: <file> | <format> debug`
107
+ - **Green dot** `saved <n> files (<ms>ms)`, or `saved <n>/<total> files (<ms>ms)` when items were skipped (Multiple images)
108
+ - **Yellow ring** `disk <n>% full`, or `empty array` (Multiple images with an empty array)
109
+ - **Red ring** `Error`
101
110
 
102
111
  ## Error Handling
103
112
 
104
- Common errors and solutions:
105
- - **"Folder path not configured"**: Ensure folder path is set
106
- - **"Invalid image structure"**: Check input is valid image data
107
- - **"Cannot create directory"**: Verify write permissions
108
- - **"Too many file variations"**: Clean up old files (>1000 with same timestamp)
113
+ A failure is reported with `node.error` as `Error saving image: <message>` (a Catch node receives it), followed by a `Hint: ...` warning when the node can suggest one. Common messages:
114
+ - **"Folder path is not configured or resolved."**: the `msg`, `flow` or `global` value of Folder Path is missing or empty
115
+ - **"No image data found at specified input path"**: nothing at **Input from**
116
+ - **"Invalid image structure"**: the raw image object is not valid (see the warning logged before it)
117
+ - **"Cannot create directory: ..."**: the folder cannot be created; check the permissions
118
+ - **"Too many file variations exist"**: the name and all its variations up to `_999` already exist
119
+ - **"BMP output requires raw image data, not an encoded buffer"**
120
+ - **"Input must resolve to an array or object."** and **"All `<n>` items failed."** (Multiple images). A single item that fails is skipped with a warning such as `Item 3: no image at "bitmap", skipping.`
109
121
 
110
122
  ## Examples
111
123
 
@@ -113,13 +125,13 @@ Common errors and solutions:
113
125
  ```javascript
114
126
  // Input: Processed image
115
127
  // Config: Folder="/output", Format="jpg"
116
- // Result: /output/image_20240109_143022.jpg
128
+ // Result: /output/image_20240109_143022-517Z.jpg
117
129
  ```
118
130
 
119
131
  ### Custom Prefix for Source Identification
120
132
  ```javascript
121
133
  // Config: Prefix="camera1", Folder="/surveillance"
122
- // Result: /surveillance/camera1_20240109_143022.jpg
134
+ // Result: /surveillance/camera1_20240109_143022-517Z.jpg
123
135
  ```
124
136
 
125
137
  ### Format Conversion
@@ -136,11 +148,19 @@ Common errors and solutions:
136
148
  // Result: Saves to dynamic folder location
137
149
  ```
138
150
 
151
+ ### Fixed Name from the Message
152
+ ```javascript
153
+ // msg.serial = "SN1234"
154
+ // Config: Full Filename (JSONata) = serial & ".png", Folder="/archive"
155
+ // Result: /archive/SN1234.png in PNG, whatever Output Format is set to
156
+ ```
157
+
139
158
  ### Overwrite Protection in Action
140
159
  ```javascript
141
- // First save: image_20240109_143022.jpg
142
- // Second save (same second): image_20240109_143022_2.jpg
143
- // Third save: image_20240109_143022_3.jpg
160
+ // Config: Full Filename="last.jpg"
161
+ // First save: last.jpg
162
+ // Second save: last_2.jpg
163
+ // Third save: last_3.jpg
144
164
  ```
145
165
 
146
166
  ## Tips & Best Practices
@@ -148,34 +168,35 @@ Common errors and solutions:
148
168
  1. **Use Prefixes**: Identify image sources with meaningful prefixes
149
169
  2. **Enable Protection**: Keep overwrite protection on to prevent data loss
150
170
  3. **Choose Format Wisely**:
151
- - JPEG for photos (smaller files)
152
- - PNG for graphics with transparency
153
- - WebP for web optimization
154
- - BMP for uncompressed archival or when lossless pixel-exact output is needed
155
- 4. **Button Control**: Disable during development to prevent unwanted saves
156
- 5. **Monitor Status**: Check node status for save confirmations
171
+ - JPEG for photos (smaller files, no alpha)
172
+ - PNG for graphics with transparency, or lossless output
173
+ - WebP for small files, lossy or lossless
174
+ - BMP for uncompressed, pixel-exact output
175
+ 4. **Button Control**: Switch the node off during development to prevent unwanted saves
176
+ 5. **Rolling Archive**: Set **Max Images** on a dedicated folder to keep only the most recent files
157
177
 
158
178
  ## Integration Examples
159
179
 
160
180
  ### Computer Vision Pipeline
161
181
  ```
162
- [Camera] → [Object Detection] → [Draw Boxes] → [Image-Out]
182
+ [Camera] → [Object Detection] → [Add-BBs] → [Image-Out]
163
183
  ```
164
184
  Save annotated detection results with timestamps.
165
185
 
166
186
  ### Batch Processing
167
187
  ```
168
- [Image-In] → [Array-Out] → [Transform] → [Image-Out]
188
+ [Function: build items] → [Image-Out: Multiple images]
169
189
  ```
170
- Process and save multiple images with automatic naming.
190
+ Save every image of one message, each to its own folder and file name, from an array of `{ bitmap, outputDir, filename }` items.
171
191
 
172
192
  ### Quality Control
173
193
  ```
174
- [Inspection Camera] → [Defect Detection] → [Image-Out (active/inactive)]
194
+ [Inspection Camera] → [Defect Detection] → [Switch: defect found] → [Image-Out]
175
195
  ```
176
- Conditionally save images based on detection results.
196
+ Save only the images in which a defect was found.
177
197
 
178
198
  ## Related Nodes
179
- - **[image-in](image-in.md)**: Load images from filesystem
180
- - **[array-out](array-out.md)**: Process multiple images before saving
181
- - **[filter](../transform/filter.md)**: Apply enhancements before saving
199
+ - **[image-in](./image-in.md)**: Load images from filesystem
200
+ - **[folder-in](./folder-in.md)**: Read the images of a folder one by one
201
+ - **[add-bbs](../blend/add-bbs.md)**: Draw detections before saving
202
+ - **[filter](../transform/filter.md)**: Apply enhancements before saving
@@ -1,108 +1,154 @@
1
+ ---
2
+ title: "Advanced Mosaic Node - Canvas Layout with Resize and Rotation"
3
+ description: "Compose the images of an array on a canvas in Node-RED with a position, size, rotation and stacking order per image. Part of @rosepetal/node-red-contrib-image-tools."
4
+ head:
5
+ - - meta
6
+ - name: "keywords"
7
+ content: "node-red, advanced mosaic, canvas, image layout, rotation, layering, mask propagation, opencv, rosepetal"
8
+ - - meta
9
+ - property: "og:title"
10
+ content: "Advanced Mosaic Node - @rosepetal/node-red-contrib-image-tools"
11
+ - - meta
12
+ - property: "og:description"
13
+ content: "Compose the images of an array on a canvas in Node-RED with a position, size, rotation and stacking order per image."
14
+ ---
15
+
1
16
  # Advanced Mosaic Node
2
17
 
3
18
  ## Purpose & Use Cases
4
19
 
5
- The `advanced-mosaic` node provides sophisticated layout capabilities beyond basic grids, supporting custom positioning, variable cell sizes, and complex arrangement patterns. It enables pixel-perfect control over image placement for professional layouts and artistic compositions.
20
+ The `advanced-mosaic` node composes the images of an array on a canvas of a fixed size. For each placement it sets a position, an optional new size, a rotation and a stacking order, laid out in a visual editor. Unlike [mosaic](./mosaic.md), images can be resized and rotated, and rotated images are blended over what is below them. It can also carry a mask per image through the same steps.
6
21
 
7
22
  **Real-World Applications:**
8
- - **Magazine Layouts**: Create complex editorial layouts with varying image sizes
9
- - **Web Design Mockups**: Arrange elements in custom positions for design prototypes
10
- - **Artistic Compositions**: Create asymmetric, visually interesting image arrangements
11
- - **Dashboard Design**: Position charts and data visualizations with precise control
12
- - **Poster Creation**: Design promotional materials with sophisticated image arrangements
13
-
14
- *[PLACEHOLDER - Add GIF showing complex layouts with custom positioning and variable cell sizes]*
23
+ - **Inspection Reports**: Place a full view and enlarged details of a part on one image
24
+ - **Multi-Camera Views**: Combine the images of several cameras, scaled and turned to a common orientation
25
+ - **Overlay Compositions**: Stack images in a chosen order
26
+ - **Segmentation Output**: Move the masks of each image to the composed canvas together with the image
15
27
 
16
28
  ## Input/Output Specification
17
29
 
18
30
  ### Inputs
19
- - **Image Array**: Array of image objects with optional position metadata
20
- - **Layout Configuration**: Custom positioning data via message properties or configuration
21
- - **Canvas Parameters**: Target canvas dimensions and layout constraints
31
+ - **Image Array**: an array of raw image objects or encoded JPEG/PNG/WebP/BMP `Buffer`s, read from **Input from** (`msg.payload` by default). A single image is treated as an array of one.
32
+ - **Placements**: set in the node's **Visual Canvas Editor**, not taken from the message.
33
+ - **Canvas Width / Canvas Height**: a number, or read from `msg`, `flow` or `global` for each message.
34
+ - **Masks** (optional, with **Propagate masks**): an array aligned with the images, read from **Masks from** (`msg.masks` by default). See [Mask Propagation Input Format](#mask-propagation-input-format).
22
35
 
23
36
  ### Outputs
24
- - **Complex Layout**: Single composite image with precisely positioned elements
25
- - **Custom Canvas**: Canvas sized according to layout requirements or fixed dimensions
26
- - **Format Options**: Raw image object or encoded file formats
27
- - **Mask Propagation (optional)**: When enabled, a second output array containing masks transformed with the exact same resize/rotate/position steps. Each mask index aligns with the source image index and is ready for downstream drawing/overlay nodes.
37
+ One output:
38
+ - **Composite Image**: one image of Canvas Width × Canvas Height, written to **Output to** (`msg.payload` by default), as a raw image object or an encoded `Buffer` (JPEG/PNG/WebP)
39
+ - **Masks** (with **Propagate masks**): written to **Masks to** (`msg.masks` by default)
40
+ - `msg.performance.rpimage.<key>`: `{ conversion, task, total }` in milliseconds
28
41
 
29
42
  ## Configuration Options
30
43
 
31
- ### Input/Output Paths
32
- - **Input From**: `msg.payload` (default), `flow.*`, `global.*`
33
- - **Output To**: `msg.payload` (default), `flow.*`, `global.*`
34
-
35
- ### Canvas Configuration
36
-
37
- #### Canvas Size
38
- - **Fixed Dimensions**: Specify exact width and height
39
- - **Auto Size**: Calculate canvas size based on image positions and sizes
40
- - **Aspect Ratio**: Maintain specific aspect ratio while auto-sizing
41
-
42
- #### Background Settings
43
- - **Background Color**: Color for empty canvas areas
44
- - **Background Image**: Use image as background behind positioned elements
45
- - **Transparency**: Support for transparent backgrounds (PNG output)
46
-
47
- ### Positioning System
48
-
49
- #### Position Modes
50
- - **Absolute**: X,Y coordinates in pixels
51
- - **Relative**: Positions as percentages of canvas size (0-1)
52
- - **Grid-Based**: Enhanced grid system with custom cell sizes
53
- - **Flow Layout**: Automatic positioning with spacing rules
44
+ | Property | Default | Meaning |
45
+ |----------|---------|---------|
46
+ | Name | empty | Label of the node; also the key of its timings in `msg.performance.rpimage` |
47
+ | Input from | `msg.payload` | Where the array is read (`msg`, `flow` or `global`) |
48
+ | Output to | `msg.payload` | Where the composite is written (`msg`, `flow` or `global`) |
49
+ | Propagate masks | off | Transform a mask per image together with its image |
50
+ | Masks from | `msg.masks` | Where the masks are read |
51
+ | Masks to | `msg.masks` | Where the transformed masks are written |
52
+ | 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) |
53
+ | Debug / Debug Width | off / `200` | **Show processed image** under the node in the editor |
54
+ | Canvas Width | `800` | Width of the canvas in pixels; **Apply Canvas Size** updates the visual editor |
55
+ | Canvas Height | `600` | Height of the canvas in pixels |
56
+ | Background Color | `#000000` | Colour of the canvas where no image is placed (opaque) |
57
+ | Visual Canvas Editor | none | The placements. Opening the edit dialog of a node without placements adds one: image 0 at (50, 50), resized to 200 × 150 |
58
+ | Inference | off | Under **Advanced options**: **Transform inference coordinates**, with **Inf. Input** and **Inf. Output** (both `msg.inference`) |
59
+
60
+ ### Visual Canvas Editor
61
+ Each placement is a rectangle on a scaled view of the canvas. Drag it to move it; **Add Image**, **Remove Selected**, **Duplicate**, **Bring to Front** and **Send to Back** manage the placements, and **Show Grid**, **Snap to Grid**, **Magnetic Snap** and **Lock Aspect Ratio** help the layout. The properties panel of the selected placement has:
62
+
63
+ | Field | Meaning |
64
+ |-------|---------|
65
+ | Array Index | Which image of the input array is placed (0 = first), asked by **Add Image** and read-only afterwards. A placement whose index is outside the array is ignored |
66
+ | Resize Width / Resize Height | New size in pixels. Empty keeps the original size; with only one of them, the other follows the aspect ratio. Bilinear interpolation |
67
+ | Rotation (°) | Rotation after the resize, around the image centre, on a canvas grown to fit the rotated image. See the note below on the direction |
68
+ | X Position / Y Position | Where the top-left corner of the (resized and rotated) image goes, in pixels. The part outside the canvas is cut off |
69
+ | Z-Index | Stacking order: lower values are drawn first, higher values on top |
70
+
71
+ The preview draws each placement from its **Input Width** and **Input Height**, asked by **Add Image** (800 × 600 for the first placement) and read-only afterwards; at runtime the real size of each image is used.
72
+
73
+ **Rotation direction**: positive angles turn the image clockwise, as in the editor's preview, except exactly 90° and 270°: 90° turns it counter-clockwise and 270° clockwise. Use for example 89.9° or −90° for a quarter turn clockwise.
74
+
75
+ ### Canvas and Blending
76
+ - When any placement has a rotation, the canvas is RGBA (and opaque). The corners uncovered by each rotation are transparent, so the background and the images below show through; images are blended over the canvas with their alpha channel.
77
+ - Without rotations, the canvas takes the color space of the inputs (RGBA if any image is RGBA, else BGRA, RGB, BGR and GRAY, in that order) and images replace the pixels below them, except on an RGBA canvas, where images with an alpha channel are blended over it.
54
78
 
55
- #### Position Sources
56
- - **Configuration**: Set positions in node editor
57
- - **Message Data**: Position data provided per image in input array
58
- - **Dynamic Calculation**: Calculate positions using function nodes
79
+ ### Output Format Options
80
+ - **Raw**: Standard image object (fastest between image nodes)
81
+ - **JPEG**: Compressed; the alpha channel is dropped
82
+ - **PNG**: Lossless, keeps the alpha channel
83
+ - **WebP**: Keeps the alpha channel
59
84
 
60
- ### Advanced Layout Features
85
+ ## Mask Propagation Input Format
61
86
 
62
- #### Variable Cell Sizes
63
- - **Custom Width/Height**: Each image can have different cell dimensions
64
- - **Aspect Ratio Preservation**: Maintain image proportions within custom cells
65
- - **Scaling Options**: Fit, fill, or stretch images within designated areas
87
+ When *Propagate masks* is checked, supply `msg.masks` (or the configured path) as an **array aligned with the input images array**: index `i` is the mask of image `i`. Each entry can be one of:
66
88
 
67
- #### Layering and Z-Order
68
- - **Layer Control**: Specify which images appear above others
69
- - **Overlap Handling**: Manage overlapping elements gracefully
70
- - **Transparency Support**: Proper alpha blending for overlapping areas
89
+ - **Polygon mask**: `{ tag?: "class", polygons: [ [ [x,y], [x,y], ... ], ... ] }` where points are normalized 0–1 in the image.
90
+ - **Mask image**: `{ mask: { data, width, height, channels, colorSpace, dtype }, tag?: "class" }`, an encoded image `Buffer` in `mask`, or the raw image object itself.
91
+ - **2D matrix mask**: `{ mask: [[0,1,1,...], ...], tag?: "class" }` or the 2D numeric matrix itself.
71
92
 
72
- ### Output Format Options
73
- - **Raw**: Standard image object (fastest for processing chains)
74
- - **JPEG**: Compressed (transparency becomes background color)
75
- - **PNG**: Full transparency and quality preservation
76
- - **WebP**: Modern format with transparency and compression
77
- - **Mask Propagation**: Enable the *Propagate masks* checkbox to feed a mask array (one per input image index). The node applies the same resize/rotate/position to each mask and emits a transformed mask array for downstream overlay/drawing without manual conversions.
93
+ Rules:
94
+ - If the masks input is not an array, the node warns `Mask propagation enabled but masks input is not an array; skipping mask propagation.` and composes the image only.
95
+ - Entries after the last image, and entries of another shape, are ignored.
96
+ - The label is read from `tag`, `class_name`, `className`, `label` or `class` and returned as `tag`.
97
+ - Masks are made binary (any value above 0 becomes 255; color masks are converted to gray first; in a 2D matrix, values up to 1 are multiplied by 255 first, so values below 1/255 and negative values count as 0), resized with nearest-neighbour interpolation, rotated and positioned like their image. At exactly 90°, 180° and 270° the mask is not rotated: it is placed as it is at the position of the image.
78
98
 
79
- ## Mask Propagation Input Format
99
+ Output: an array of `{ mask, tag? }`, where `mask` is a single-channel (`GRAY`) raw image of the canvas size. Every image with a usable mask produces an entry, in input order (all black when the image is not placed); images without one produce none, so the output array is not aligned with the input images when some have none. An image placed several times has all its placements in the same mask.
80
100
 
81
- When *Propagate masks* is enabled, supply `msg.masks` (or the configured path) as an **array aligned to the input images array**. Index `i` is the mask for image `i`. Each entry can be one of:
101
+ ### Inference
102
+ With **Transform inference coordinates** checked, **Inf. Input** must hold an array with one entry per input image, each the inference array of that image. Detections (`raw_boxes`) and segmentations (`polygons`) are mapped through each placement of their image (clipped to the canvas); other entries are copied unchanged, and the node writes a single flat array to **Inf. Output**. The mapping scales to Resize Width × Resize Height (the original width or height for an empty one, read from the raw image object, so `NaN` for an encoded `Buffer`, and without the aspect-ratio rule the image uses), rotates around the centre of that rectangle and moves it to X/Y Position. It matches the image for placements without rotation or at 180° that set both or neither resize size. For other rotations the image sits on a larger canvas, so the mapped coordinates are offset from it, and at exactly 90° and 270° they turn the opposite way to the image.
82
103
 
83
- - **Polygon mask**: `{ tag?: "class", polygons: [ [ [x,y], [x,y], ... ] , ... ] }` where points are normalized 0–1.
84
- - **Raw mask image**: `{ mask: { data, width, height, channels, colorSpace, dtype } , tag?: "class" }` (RGBA/LA/GRAY accepted; alpha preferred).
85
- - **2D matrix mask**: `{ mask: [[0,1,1,...], ...], tag?: "class" }` or simply a 2D/array-of-2D numeric matrix.
104
+ ## Status and Errors
86
105
 
87
- Rules:
88
- - Array length should match the images array; missing entries are ignored.
89
- - `tag`/`class`/`class_name`/`label` are passed through if present.
90
- - Masks are binarized, resized with `INTER_NEAREST`, rotated, and positioned exactly like their source image. The output `masks` array mirrors the input order and is ready for downstream drawing nodes.
106
+ - **Success**: green dot `OK: <n> img in <t> ms (conv <c> ms | task <k> ms)`, where `<n>` is the number of placements, with `/<m> mask` after it when masks were propagated; `OK: empty canvas in <t> ms` when no placement applies. With Debug on: `OK: 1 img in ...` plus the preview format
107
+ - **Failure**: `msg.error` is set, the **first** input image 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. An invalid array gives `Invalid image list`; a canvas size of 0 or less gives `Canvas dimensions must be positive numbers`
91
108
 
92
109
  ## Performance Notes
93
110
 
94
- ### C++ Backend Processing
95
- - **Optimized Rendering**: Efficient composite rendering with layer management
96
- - **Memory Management**: Smart memory allocation for complex layouts
97
- - **Overlap Detection**: Optimized algorithms for handling overlapping elements
98
- - **High-Quality Scaling**: Professional-grade scaling for variable-sized elements
99
-
100
- ### Layout Engine
101
- - **Position Validation**: Automatic bounds checking and constraint handling
102
- - **Layer Ordering**: Efficient z-order processing for overlapping elements
103
- - **Canvas Optimization**: Minimal canvas size calculation for auto-sizing modes
111
+ - Resizing, rotation, blending and encoding run in one call to the native OpenCV addon, on the libuv thread pool
112
+ - Rotations other than multiples of 90° need interpolation and a larger intermediate image
104
113
 
105
114
  ## Real-World Examples
106
115
 
107
- ### Magazine Article Layout
108
- ```javascript\n// In function node: set custom positions for magazine layout\nmsg.images.forEach((img, i) => {\n if (i === 0) { // Hero image\n img.position = { x: 0, y: 0, width: 800, height: 400 };\n } else if (i === 1) { // Side image\n img.position = { x: 820, y: 0, width: 300, height: 200 };\n } else { // Thumbnail strip\n img.position = { x: 100 * i, y: 420, width: 80, height: 80 };\n }\n});\n```\nCreate professional magazine-style layouts with hero images and supporting visuals.\n\n### Dashboard Layout\n```\n[Chart Images] → [Function: Set Positions] → [Advanced Mosaic: Custom layout] → [Dashboard]\n```\nPosition charts, graphs, and KPI displays in precise dashboard arrangements.\n\n### Product Showcase\n```javascript\n// Custom product display with hero and detail shots\nmsg.productImages[0].position = { x: 0, y: 0, width: 600, height: 600 }; // Main product\nmsg.productImages[1].position = { x: 620, y: 0, width: 280, height: 200 }; // Detail 1\nmsg.productImages[2].position = { x: 620, y: 220, width: 280, height: 200 }; // Detail 2\nmsg.productImages[3].position = { x: 620, y: 440, width: 280, height: 160 }; // Detail 3\n```\n\n### Artistic Collage Creation\n```\n[Art Images] → [Function: Random Positions] → [Advanced Mosaic: Overlap enabled] → [Artistic Collage]\n```\nCreate visually interesting overlapping compositions with controlled randomness.\n\n### Web Design Mockup\n```\n[UI Elements] → [Function: Responsive Positions] → [Advanced Mosaic: Fixed canvas] → [Mockup]\n```\nArrange UI elements for web design prototypes and mockups.\n\n## Common Issues & Troubleshooting\n\n### Position Conflicts\n- **Issue**: Images overlapping unintentionally or awkward positioning\n- **Solution**: Validate position calculations and implement collision detection\n- **Prevention**: Use position validation functions before processing\n\n### Canvas Size Problems\n- **Issue**: Canvas too small for positioned elements or excessive whitespace\n- **Solution**: Use auto-sizing or carefully calculate required canvas dimensions\n- **Planning**: Consider element positions and sizes when planning canvas\n\n### Performance with Complex Layouts\n- **Issue**: Slow processing with many overlapping elements\n- **Optimization**: Minimize unnecessary overlaps, use appropriate image sizes\n- **Monitoring**: Track processing times and optimize layout complexity\n\n### Memory Issues\n- **Issue**: Large canvases with high-resolution images consume excessive memory\n- **Solution**: Use appropriately sized images for final output requirements\n- **Strategy**: Consider final display size when sizing source images\n\n## Integration Patterns\n\n### Professional Layout Workflow\n```\nContent → Analyze Layout → Calculate Positions → Advanced Mosaic → Output\n```\nAutomated professional layout generation based on content analysis.\n\n### Interactive Design System\n```\nUser Input → Position Calculator → Advanced Mosaic → Preview → Iterate\n```\nInteractive layout system for design applications.\n\n### Template-Based Generation\n```\nLayout Template → Apply to Content → Advanced Mosaic → Branded Output\n```\nUse predefined templates for consistent branded layouts.\n\n### Responsive Layout System\n```\nContent → Detect Screen Size → Calculate Responsive Positions → Advanced Mosaic → Adaptive Output\n```\nCreate layouts that adapt to different output dimensions.\n\n## Advanced Usage\n\n### Template-Based Positioning\n```javascript\n// Define layout templates\nconst templates = {\n hero: {\n main: { x: 0, y: 0, width: 0.7, height: 1.0 },\n sidebar: [ \n { x: 0.72, y: 0, width: 0.28, height: 0.3 },\n { x: 0.72, y: 0.32, width: 0.28, height: 0.3 },\n { x: 0.72, y: 0.64, width: 0.28, height: 0.36 }\n ]\n },\n grid: {\n // Define grid-based template\n }\n};\n\nmsg.layout = templates[msg.layoutType];\n```\n\n### Responsive Position Calculation\n```javascript\n// Calculate positions based on canvas size\nfunction calculateResponsivePositions(images, canvasWidth, canvasHeight) {\n return images.map((img, i) => {\n // Implement responsive positioning logic\n const position = {\n x: Math.floor((i % 3) * canvasWidth / 3),\n y: Math.floor(Math.floor(i / 3) * canvasHeight / 3),\n width: canvasWidth / 3 - 10,\n height: canvasHeight / 3 - 10\n };\n return { ...img, position };\n });\n}\n```\n\n### Overlap Management\n```javascript\n// Detect and resolve position conflicts\nfunction resolveOverlaps(elements) {\n for (let i = 0; i < elements.length; i++) {\n for (let j = i + 1; j < elements.length; j++) {\n if (elementsOverlap(elements[i], elements[j])) {\n // Implement overlap resolution strategy\n adjustPosition(elements[j], elements[i]);\n }\n }\n }\n return elements;\n}\n```\n\n### Dynamic Layout Optimization\n```javascript\n// Optimize layout based on content analysis\nfunction optimizeLayout(images, canvasSize) {\n // Analyze image importance, size requirements, etc.\n const important = images.filter(img => img.priority === 'high');\n const secondary = images.filter(img => img.priority === 'medium');\n const background = images.filter(img => img.priority === 'low');\n \n // Position important images first, then fill with secondary\n return arrangeByPriority(important, secondary, background, canvasSize);\n}\n```\n\n## Best Practices\n\n### Layout Design\n- Plan layouts on paper or design tools before implementing\n- Use consistent spacing and alignment principles\n- Consider visual hierarchy and reading patterns\n- Test layouts with different content variations\n\n### Position Management\n- Use relative positioning for responsive layouts\n- Implement position validation to prevent errors\n- Consider overlap handling strategies from the start\n- Document position calculation logic for maintenance\n\n### Performance Optimization\n- Use appropriate image sizes for final output requirements\n- Minimize unnecessary overlapping elements\n- Consider memory implications of large canvas sizes\n- Profile performance with realistic content loads\n\n### Quality Considerations\n- Use high-quality source images for scaling operations\n- Choose appropriate output formats for intended use\n- Consider compression settings for web vs. print\n- Test final output in intended display environment\n\n### Development Workflow\n- Start with simple positioning and add complexity gradually\n- Use debug output to verify position calculations\n- Implement position validation and error handling\n- Create reusable positioning templates for consistency
116
+ ### Overview and Detail
117
+ Placements (canvas 1200 × 600, input array: full view, close-up):
118
+
119
+ | Array Index | Resize Width | Resize Height | Rotation (°) | X Position | Y Position | Z-Index |
120
+ |-------------|--------------|---------------|--------------|------------|------------|---------|
121
+ | 0 | 800 | | 0 | 0 | 0 | 0 |
122
+ | 1 | 400 | | 0 | 800 | 0 | 1 |
123
+
124
+ ```
125
+ [Camera A] → [Array-In: pos=0] ┐
126
+ [Camera B] → [Array-In: pos=1] ├→ [Array-Out] → [Advanced Mosaic] → [Image-Out]
127
+ ```
128
+ Array-In and Array-Out are part of [`@rosepetal/node-red-contrib-utils`](https://docs.rosepetal.ai/flows/node-red-contrib-utils/nodes/io/array-in).
129
+
130
+ ### Masks Follow the Layout
131
+ ```
132
+ [Images + segmentation] → [Function: msg.masks = one { polygons, tag } per image] → [Advanced Mosaic: Propagate masks] → [Add-Masks: Image msg.payload, Masks Array msg.masks]
133
+ ```
134
+ The composed image and the masks in canvas coordinates leave the node together.
135
+
136
+ ## Common Issues & Troubleshooting
137
+
138
+ ### Image Not Visible
139
+ - **Issue**: A placement does not appear
140
+ - **Solution**: Check that its **Array Index** exists in the input array, that its position is inside the canvas, and that no placement with a higher **Z-Index** covers it
141
+
142
+ ### Quarter Turn in the Wrong Direction
143
+ - **Issue**: A rotation of exactly 90° or 270° turns the opposite way to the preview
144
+ - **Solution**: See the note on rotation direction above; use −90° (or 270°) for clockwise
145
+
146
+ ### Four Channels in the Output
147
+ - **Issue**: The output is RGBA although the inputs are RGB
148
+ - **Cause**: Any rotation makes the canvas RGBA (it stays opaque)
149
+ - **Solution**: Convert to RGB with [color-convert](../transform/color-convert.md) if a 3-channel image is needed
150
+
151
+ ### Masks Out of Step with the Images
152
+ - **Issue**: Mask `i` of the output does not belong to image `i`
153
+ - **Cause**: Images without a mask produce no entry
154
+ - **Solution**: Use the `tag` of each mask, or give every image a mask