@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,26 +1,43 @@
1
+ ---
2
+ title: "Add-Masks Node - Polygon Masks Colored by Class"
3
+ description: "Blend several polygon masks over an image in Node-RED, with a color per class name and a global mask strength. Part of @rosepetal/node-red-contrib-image-tools."
4
+ head:
5
+ - - meta
6
+ - name: "keywords"
7
+ content: "node-red, add-masks, polygon masks, segmentation, class colors, object detection, opencv, rosepetal"
8
+ - - meta
9
+ - property: "og:title"
10
+ content: "Add-Masks Node - @rosepetal/node-red-contrib-image-tools"
11
+ - - meta
12
+ - property: "og:description"
13
+ content: "Blend several polygon masks over an image in Node-RED, with a color per class name and a global mask strength."
14
+ ---
15
+
1
16
  # add-masks
2
17
 
3
- Applies multiple polygon-based masks to a base image using weighted blending with configurable mask strength and class-based color mapping.
18
+ Applies several polygon or bitmap masks to a base image, each tinted with the colour of its class, with one mask strength for all.
4
19
 
5
20
  ## Description
6
21
 
7
- The `add-masks` node extends the functionality of `add-mask` to handle multiple masks with automatic color assignment based on class names. It processes arrays of mask objects where each mask can have a different color based on its `class_name` property. Undefined classes can automatically receive randomly generated colors for visual distinction.
22
+ The `add-masks` node extends [add-mask](./add-mask.md) to an array of masks. Each mask carries a class name; classes listed in **Class Color Mappings** get the colour set there, and the others get a colour picked automatically. Where masks overlap, only the mask of the class with the highest priority is painted.
8
23
 
9
- This node is ideal for visualizing object detection results, semantic segmentation, or any scenario where multiple regions need to be highlighted with different colors based on their classification.
24
+ This node is meant for showing segmentation results on the original image.
10
25
 
11
26
  ## Input Structure
12
27
 
13
- The node consumes an array of mask objects. It now accepts the exact segmentation output produced by the Rosepetal **inferencer** node (no manual conversion required):
28
+ The node reads an array of mask objects. It accepts the segmentation output of the Rosepetal inferencer node directly:
14
29
 
15
- - **Class name**: `tag`, `class_name`, `className`, `label`, or `class`
30
+ - **Class name** (required): `tag`, `class_name`, `className`, `label` or `class` (the first non-empty string)
16
31
  - **Geometry** (one of):
17
32
  - `polygons`: array of polygons; each polygon is an array of `[x, y]` points in **normalized** coordinates (0‑1)
18
- - `mask`: either a raw mask image `{data, width, height, channels, colorSpace, dtype}` (inferencer “mask” format) or a 2D matrix/array-of-matrices with numeric values (0/1 or 0‑255)
19
- - Any extra fields are ignored. If both `polygons` and `mask` exist, polygons take priority.
33
+ - `mask`: a mask image `{data, width, height, channels, colorSpace, dtype}`, a 2D matrix of numbers, or an array of 2D matrices (only the first one is drawn)
34
+ - Any extra fields are ignored. If an object has valid `polygons`, they are used and `mask` is ignored.
35
+
36
+ Mask images and matrices are made binary (any non-zero value is inside the mask; for a 4-channel image the alpha channel is used, for a 3-channel image its gray value; matrix values below 1/255, negative ones included, count as zero) and scaled to the size of the base image with nearest-neighbour interpolation.
20
37
 
21
38
  **Example (direct inferencer output)**
22
39
  ```javascript
23
- msg.payload = [
40
+ msg.array = [
24
41
  {
25
42
  tag: "bottle",
26
43
  polygons: [[[0.1, 0.1], [0.9, 0.1], [0.9, 0.8], [0.1, 0.8]]]
@@ -30,8 +47,8 @@ msg.payload = [
30
47
  mask: {
31
48
  width: 512,
32
49
  height: 512,
33
- channels: 4,
34
- colorSpace: "RGBA",
50
+ channels: 1,
51
+ colorSpace: "GRAY",
35
52
  dtype: "uint8",
36
53
  data: <Buffer ...>
37
54
  }
@@ -42,53 +59,40 @@ msg.payload = [
42
59
  ## Configuration
43
60
 
44
61
  ### Paths
45
- - **Image**: Message property path containing the base image (default: `payload.image`)
46
- - **Masks Array**: Message property path containing the masks array (default: `payload`)
47
- - **Output**: Message property path for the result (default: `payload`)
62
+ 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.
63
+ - **Image**: the base image, a raw image object or an encoded JPEG/PNG/WebP/BMP `Buffer` (default: `msg.image`)
64
+ - **Masks Array**: the array of masks (default: `msg.array`)
65
+ - **Output**: where the result is written (default: `msg.payload`), with the size and color space of the base image
48
66
 
49
67
  ### Processing Options
50
- - **Global Mask Strength**: 0-100% intensity of mask application (default: 50%)
51
- - **Output Format**: Raw (fastest), JPEG, PNG, or WebP
52
- - **Quality**: Compression quality for JPEG/WebP (1-100)
68
+ - **Global Mask Strength**: 0-100 % (default 50): inside a mask each pixel becomes image × (100 − strength) / 100 + class colour × strength / 100
69
+ - **Output Format**: Raw (fastest), JPEG, PNG or WebP, with Quality (`90`), PNG Optimize and the WebP options as in [resize](../transform/resize.md#output-format-options)
70
+ - **Debug / Debug Width**: **Show processed image** under the node in the editor (default width 200)
71
+
72
+ The editor has no Name field for this node, so its timings are recorded under `msg.performance.rpimage.rp_add_masks`.
53
73
 
54
74
  ### Dynamic Class Color Mapping
55
75
 
56
- The node provides a dynamic interface for managing class-to-color mappings:
76
+ **Class Color Mappings** is a list of class names, each with a colour:
57
77
 
58
- #### Features:
59
- - **Add/Remove Mappings**: Dynamic addition and removal of class color pairs
60
- - **Real-time Validation**:
61
- - Duplicate class name detection
62
- - Similar color warnings (RGB distance < 50)
63
- - **Visual Feedback**: Color swatches and warning indicators
78
+ 1. Click **Add Class Mapping** to create an entry (red by default)
79
+ 2. Enter the class name (e.g., "dog") exactly as it appears in the masks
80
+ 3. Pick the colour with the colour picker
81
+ 4. Remove an entry with its trash button; drag the ☰ handle to reorder
64
82
 
65
- #### Usage:
66
- 1. Click "Add Class Mapping" to create new entries
67
- 2. Enter class name (e.g., "dog", "cat", "zebra")
68
- 3. Select desired color using color picker
69
- 4. Remove unwanted mappings with trash button
83
+ The editor warns about duplicate class names and about colours that are very close to each other.
70
84
 
71
85
  ## Color Assignment Priority
72
86
 
73
- Colors are assigned using this priority order:
74
-
75
- 1. **User-defined mapping**: Colors explicitly set in the class color mappings
76
- 2. **Auto-generated**: Seeded random colors (always enabled)
77
- 3. **Default fallback**: White color (#ffffff)
87
+ 1. **User-defined mapping**: the colour set in Class Color Mappings
88
+ 2. **Automatic**: for other classes, the colour of a fixed palette of 216 colours that differs most from the colours already in use. The colour chosen for a class name is kept for as long as Node-RED runs, so a class keeps its colour from message to message
78
89
 
79
90
  ## Mask Priority System
80
91
 
81
- When multiple masks overlap on the same pixel, only **one mask is painted** based on priority order.
82
-
83
- ### Priority Rules
92
+ When several masks cover the same pixel, only **one mask is painted**:
84
93
 
85
- 1. **Class Color Mappings Priority**: Classes listed first in the "Class Color Mappings"
86
- configuration have higher priority. Drag rows to reorder.
87
-
88
- 2. **Unmapped Class Tie-breaking**: If neither overlapping mask has a class defined
89
- in the mappings, the mask that appears first in the input results array wins.
90
-
91
- 3. **Mixed Priority**: Mapped classes always take priority over unmapped classes.
94
+ 1. Classes listed in Class Color Mappings come first, in the order of the list (top = highest priority).
95
+ 2. Unmapped classes come after all mapped classes, in the order of the input array.
92
96
 
93
97
  ### Example
94
98
 
@@ -100,185 +104,59 @@ Class Color Mappings (drag to reorder):
100
104
  3. "dog" → #0000FF (blue) ← Lowest mapped priority
101
105
  ```
102
106
 
103
- If a pixel is covered by both "person" and "car" masks, only the **red (person)**
104
- color will be painted.
105
-
106
- If a pixel is covered by "cat" and "bird" (both unmapped), the one appearing
107
- first in the input array will be painted.
108
-
109
- ### Reordering Classes
110
-
111
- In the Node-RED editor:
112
- 1. Click and drag the ☰ handle next to any class row
113
- 2. Drop it in the desired position
114
- 3. Top = highest priority, bottom = lowest priority
107
+ If a pixel is covered by both "person" and "car" masks, only the **red (person)** colour is painted. If a pixel is covered by "cat" and "bird" (both unmapped), the one appearing first in the input array is painted.
115
108
 
116
- ## Processing Flow
109
+ ## Outputs, Status and Errors
117
110
 
118
- 1. **Structure Validation**: Validates the nested array structure
119
- 2. **Color Resolution**: Builds color map from configuration and auto-generation
120
- 3. **Mask Generation**: Creates binary masks for each polygon using OpenCV
121
- 4. **Multi-layer Blending**: Applies all masks with proper weight normalization
122
- 5. **Output Encoding**: Converts to specified format with quality settings
111
+ - **Output**: the image with the masks; `msg.performance.rpimage.rp_add_masks`: `{ conversion, task, total }` in milliseconds
112
+ - **Status**: green dot `OK: <n> img in <t> ms (conv <c> ms | task <k> ms)`, where `<n>` is the number of polygons and masks counted in the input (one per polygon, per mask image and per valid matrix, even those that are not drawn)
113
+ - **Empty array**: the base image is written to Output unchanged and the status shows `OK: 0 img ...`
114
+ - **Validation**: the whole message fails if any entry is invalid. The node sets `msg.error` (with `validationError: true`), writes the base image to Output, logs a warning, shows a red ring `Error: <first 30 characters>` and still sends the message. Messages include `Masks input must be an array`, `Base image is invalid or missing`, `Mask at index <i> is missing a valid class/tag field`, `Mask at index <i> must include either 'polygons' or 'mask'`, `Invalid coordinate at index <i>.polygons[<j>][<k>]: coordinates must be in range [0, 1]` and `Invalid mask data at index <i>: expected raw mask image or 2D matrix`
123
115
 
124
116
  ## Examples
125
117
 
126
- ### Basic Object Detection Visualization
118
+ ### Segmentation Visualization
127
119
 
128
120
  **Input:**
129
121
  ```javascript
130
- msg.payload = [
131
- {
132
- masks: [
133
- {
134
- mask: [[[0.1,0.1], [0.3,0.1], [0.3,0.3], [0.1,0.3]]],
135
- class_name: "dog"
136
- },
137
- {
138
- mask: [[[0.5,0.5], [0.7,0.5], [0.7,0.7], [0.5,0.7]]],
139
- class_name: "cat"
140
- }
141
- ]
142
- }
122
+ msg.image = originalImage;
123
+ msg.array = [
124
+ { tag: "dog", polygons: [[[0.1,0.1], [0.3,0.1], [0.3,0.3], [0.1,0.3]]] },
125
+ { tag: "cat", polygons: [[[0.5,0.5], [0.7,0.5], [0.7,0.7], [0.5,0.7]]] }
143
126
  ];
144
127
  ```
145
128
 
146
129
  **Configuration:**
147
130
  - dog → Red (#FF0000)
148
131
  - cat → Blue (#0000FF)
149
- - Global Mask Strength: 70%
150
-
151
- **Result:** Image with red rectangle for dog and blue rectangle for cat
152
-
153
- ### Semantic Segmentation with Auto-Colors
154
-
155
- **Input:** Multiple elements with various class names
156
-
157
- **Configuration:**
158
- - Only define colors for important classes
159
- - System automatically generates colors for others
160
-
161
- **Result:** Consistent coloring with user-defined colors for key classes and auto-generated colors for others
162
-
163
- ## Performance Characteristics
132
+ - Global Mask Strength: 70
164
133
 
165
- ### Optimizations
166
- - **C++ Backend**: OpenCV-powered processing with SIMD optimizations
167
- - **Batch Processing**: All masks processed in single C++ call
168
- - **Weight Normalization**: Prevents over-saturation when masks overlap
169
- - **Memory Efficiency**: Reuses intermediate buffers across masks
134
+ **Result:** the image with a red square for the dog and a blue square for the cat.
170
135
 
171
- ### Timing Breakdown
172
- Status displays show detailed timing:
173
- - **Convert**: Time for input validation and format conversion
174
- - **Task**: Time for mask generation and blending in C++
175
- - **Encode**: Time for output format encoding (if not raw)
136
+ ### Many Classes with Automatic Colours
176
137
 
177
- ## Error Handling
178
-
179
- ### Input Validation
180
- - **Structure validation**: Comprehensive checking of nested array format
181
- - **Coordinate validation**: Ensures normalized range (0-1) for all coordinates
182
- - **Class name validation**: Checks for non-empty string class names
183
- - **Missing mask[0]**: Specific error for missing coordinate arrays
184
-
185
- ### Visual Feedback
186
- - **Duplicate class warnings**: Real-time detection of duplicate class names
187
- - **Color conflict warnings**: Alerts for visually similar colors
188
- - **Processing status**: Shows number of masks processed and timing
189
-
190
- ## Advanced Features
191
-
192
- ### HSV-Based Color Generation
193
- Auto-generated colors use HSV color space for better visual distinction:
194
- - **Seeded randomization**: Consistent colors based on class name hash
195
- - **Optimal distribution**: 70-100% saturation and value for vibrant colors
196
- - **Visual separation**: Automatic spacing for distinguishable colors
197
-
198
- ### Multi-mask Blending Algorithm
199
- ```
200
- For each mask:
201
- 1. Generate binary mask from polygon coordinates
202
- 2. Apply mask strength weighting
203
- 3. Accumulate color contributions and total weights
204
-
205
- Final blending:
206
- result = image × (1 - total_weights) + normalized_mask_colors
207
- ```
208
-
209
- ### Overlap Handling
210
- When masks overlap, the **highest priority mask wins** and paints the pixel:
211
- - Priority determined by order in Class Color Mappings (first = highest)
212
- - Unmapped classes have lower priority than mapped classes
213
- - Among unmapped classes, input array order determines priority
214
- - Alpha blending still applies: `result = original × (1 - strength) + mask_color × strength`
215
-
216
- ## Integration Patterns
217
-
218
- ### With Object Detection Models
219
- ```javascript
220
- // Convert model output to expected format
221
- const masks = detectionResults.map(detection => ({
222
- masks: [{
223
- mask: [detection.polygon],
224
- class_name: detection.class
225
- }]
226
- }));
227
-
228
- msg.payload = masks;
229
- ```
230
-
231
- ### With Semantic Segmentation
232
- ```javascript
233
- // Process segmentation masks
234
- const masks = segmentationRegions.map(region => ({
235
- masks: [{
236
- mask: [region.contour],
237
- class_name: region.label
238
- }]
239
- }));
240
- ```
241
-
242
- ### Chaining with Other Nodes
243
- - **Upstream**: Works with `cropBB`, AI model outputs, or manual annotation tools
244
- - **Downstream**: Connect to `image-out`, display components, or further processing
245
- - **Flow integration**: Supports flow and global context for color persistence
138
+ Define colours only for the classes that matter; the others get distinct automatic colours and are painted below the mapped classes where they overlap.
246
139
 
247
140
  ## Troubleshooting
248
141
 
249
- ### Common Issues
142
+ **"Mask at index 0 is missing a valid class/tag field"**
143
+ - Every mask object needs a non-empty `tag`, `class_name`, `className`, `label` or `class`
250
144
 
251
- **"Invalid element structure"**
252
- - Check that each array element has `masks` property
253
- - Ensure `masks` is an array, not an object
145
+ **"Invalid coordinate ... coordinates must be in range [0, 1]"**
146
+ - Polygons must be normalized; divide pixel coordinates by the image width and height first
254
147
 
255
- **"Missing mask[0]"**
256
- - Verify that coordinates are in `mask[0]`, not directly in `mask`
257
- - Check that `mask` array is not empty
148
+ **"Masks input must be an array"**
149
+ - Point **Masks Array** at the array itself (default `msg.array`), not at the object that contains it
258
150
 
259
- **"Coordinates out of range"**
260
- - Ensure all coordinates are normalized (0.0-1.0)
261
- - Convert pixel coordinates to normalized before input
262
-
263
- **"Duplicate class warnings"**
264
- - Review class mappings for exact duplicates
265
- - Consider using more specific class names
151
+ **Colours change after a restart**
152
+ - Automatic colours depend on the order in which classes first appear; map the important classes to fixed colours
266
153
 
267
154
  ### Performance Tips
268
155
  - Use raw format for processing chains (fastest)
269
- - Define colors for frequently used classes to avoid repeated generation
270
- - Monitor timing display to identify bottlenecks
271
- - Process smaller images for real-time applications
156
+ - Masks are drawn and blended in the native OpenCV addon, on the libuv thread pool; a mask image of the same size as the base image avoids a resize
272
157
 
273
158
  ## Node Interactions
274
159
 
275
- ### Compatible Nodes
276
- - **Input sources**: `image-in`, `cropBB`, AI/ML model outputs
277
- - **Output destinations**: `image-out`, `concat`, display nodes
278
- - **Processing chains**: Can be chained with other blending nodes
279
- - **Context sharing**: Supports Node-RED flow and global context
280
-
281
- ### Flow Patterns
282
- - **Batch processing**: Process multiple images with same color mapping
283
- - **Interactive visualization**: Real-time mask overlay for user interfaces
284
- - **Analysis pipelines**: Combine with other image processing for complex workflows
160
+ - **Input sources**: segmentation models (for example the Rosepetal inferencer), [advanced-mosaic](../mix/advanced-mosaic.md) with **Propagate masks** (its masks carry a `tag` only when the input masks had a class name)
161
+ - **Output destinations**: [image-out](../io/image-out.md), [concat](../mix/concat.md)
162
+ - For boxes instead of masks, use [add-bbs](./add-bbs.md)