@rosepetal/node-red-contrib-image-tools 1.1.3 → 1.2.0

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 (56) hide show
  1. package/README.md +1 -13
  2. package/node-red-contrib-image-tools/lib/node-utils.js +218 -17
  3. package/node-red-contrib-image-tools/nodes/blend/add-bbs.js +64 -9
  4. package/node-red-contrib-image-tools/nodes/blend/add-mask.js +81 -9
  5. package/node-red-contrib-image-tools/nodes/blend/add-masks.js +64 -8
  6. package/node-red-contrib-image-tools/nodes/blend/blend.js +64 -10
  7. package/node-red-contrib-image-tools/nodes/io/folder-in.js +12 -1
  8. package/node-red-contrib-image-tools/nodes/io/image-in.js +10 -2
  9. package/node-red-contrib-image-tools/nodes/io/image-out.js +25 -3
  10. package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.js +52 -26
  11. package/node-red-contrib-image-tools/nodes/mix/concat.js +46 -9
  12. package/node-red-contrib-image-tools/nodes/mix/mosaic.js +52 -15
  13. package/node-red-contrib-image-tools/nodes/specialized/cropBB.js +53 -5
  14. package/node-red-contrib-image-tools/nodes/specialized/image-align.js +54 -7
  15. package/node-red-contrib-image-tools/nodes/transform/crop.js +38 -17
  16. package/node-red-contrib-image-tools/nodes/transform/draw.js +28 -7
  17. package/node-red-contrib-image-tools/nodes/transform/filter.js +34 -15
  18. package/node-red-contrib-image-tools/nodes/transform/padding.js +30 -9
  19. package/node-red-contrib-image-tools/nodes/transform/resize.js +58 -33
  20. package/node-red-contrib-image-tools/nodes/transform/rotate.js +40 -20
  21. package/node-red-contrib-image-tools/package.json +1 -8
  22. package/package.json +1 -1
  23. package/rosepetal-image-engine/binding.gyp +5 -23
  24. package/rosepetal-image-engine/src/add-mask.cpp +2 -2
  25. package/rosepetal-image-engine/src/add-masks.cpp +2 -2
  26. package/rosepetal-image-engine/src/advanced-mosaic.cpp +3 -4
  27. package/rosepetal-image-engine/src/blend.cpp +2 -2
  28. package/rosepetal-image-engine/src/concat.cpp +2 -2
  29. package/rosepetal-image-engine/src/crop.cpp +3 -3
  30. package/rosepetal-image-engine/src/draw.cpp +1 -1
  31. package/rosepetal-image-engine/src/filter.cpp +3 -3
  32. package/rosepetal-image-engine/src/mosaic.cpp +4 -5
  33. package/rosepetal-image-engine/src/padding.cpp +4 -3
  34. package/rosepetal-image-engine/src/resize.cpp +101 -23
  35. package/rosepetal-image-engine/src/rotate.cpp +3 -6
  36. package/rosepetal-image-engine/src/utils.h +46 -8
  37. package/docs/nodes/io/array-in.md +0 -119
  38. package/docs/nodes/io/array-out.md +0 -150
  39. package/docs/nodes/io/array-select.md +0 -157
  40. package/docs/nodes/io/queue.md +0 -57
  41. package/docs/nodes/io/save-file.md +0 -30
  42. package/docs/nodes/util/block-detect.md +0 -46
  43. package/node-red-contrib-image-tools/nodes/io/array-in.html +0 -110
  44. package/node-red-contrib-image-tools/nodes/io/array-in.js +0 -113
  45. package/node-red-contrib-image-tools/nodes/io/array-out.html +0 -125
  46. package/node-red-contrib-image-tools/nodes/io/array-out.js +0 -213
  47. package/node-red-contrib-image-tools/nodes/io/array-select.html +0 -156
  48. package/node-red-contrib-image-tools/nodes/io/array-select.js +0 -187
  49. package/node-red-contrib-image-tools/nodes/io/queue.html +0 -119
  50. package/node-red-contrib-image-tools/nodes/io/queue.js +0 -191
  51. package/node-red-contrib-image-tools/nodes/io/save-file.html +0 -243
  52. package/node-red-contrib-image-tools/nodes/io/save-file.js +0 -440
  53. package/node-red-contrib-image-tools/nodes/util/block-detect.html +0 -85
  54. package/node-red-contrib-image-tools/nodes/util/block-detect.js +0 -136
  55. package/node-red-contrib-image-tools/nodes/util/clean-debug.html +0 -201
  56. package/node-red-contrib-image-tools/nodes/util/clean-debug.js +0 -393
@@ -9,6 +9,7 @@
9
9
  #include <cmath>
10
10
  #include <utility>
11
11
  #include <limits>
12
+ #include <cstdlib>
12
13
  #include "utils.h"
13
14
 
14
15
  class ResizeWorker : public Napi::AsyncWorker {
@@ -59,41 +60,124 @@ protected:
59
60
  void Execute() override {
60
61
  try {
61
62
  // --- 4.1 Calcular ancho/alto objetivo --------------------------
62
- auto calcDim = [](int orig, const std::string& mode, double val) -> int {
63
+ auto safeRoundToInt = [](double value) -> int {
64
+ if (!std::isfinite(value)) {
65
+ throw std::runtime_error("Dimension must be finite (got " + std::to_string(value) + ")");
66
+ }
67
+ constexpr double kMinInt = static_cast<double>(std::numeric_limits<int>::min());
68
+ constexpr double kMaxInt = static_cast<double>(std::numeric_limits<int>::max());
69
+ if (value < kMinInt || value > kMaxInt) {
70
+ throw std::runtime_error("Dimension out of int range (got " + std::to_string(value) + ")");
71
+ }
72
+ const long long rounded = std::llround(value);
73
+ if (rounded < std::numeric_limits<int>::min() || rounded > std::numeric_limits<int>::max()) {
74
+ throw std::runtime_error("Dimension out of int range (got " + std::to_string(value) + ")");
75
+ }
76
+ return static_cast<int>(rounded);
77
+ };
78
+
79
+ auto calcDim = [&](int orig, const std::string& mode, double val) -> int {
63
80
  if (std::isnan(val)) return 0; // Auto
64
- return mode == "multiply"
65
- ? static_cast<int>(std::lround(orig * val))
66
- : static_cast<int>(std::lround(val));
81
+ if (!std::isfinite(val)) {
82
+ throw std::runtime_error("Dimension value must be finite (got " + std::to_string(val) + ")");
83
+ }
84
+ const double computed = (mode == "multiply")
85
+ ? static_cast<double>(orig) * val
86
+ : val;
87
+ try {
88
+ return safeRoundToInt(computed);
89
+ } catch (const std::exception& e) {
90
+ throw std::runtime_error(
91
+ "Dimension calc failed (mode=" + mode +
92
+ ", orig=" + std::to_string(orig) +
93
+ ", val=" + std::to_string(val) +
94
+ "): " + e.what()
95
+ );
96
+ }
67
97
  };
68
98
 
69
- targetWidth = calcDim(inputMat.cols, widthMode, widthValue);
70
- targetHeight = calcDim(inputMat.rows, heightMode, heightValue);
99
+ try {
100
+ targetWidth = calcDim(inputMat.cols, widthMode, widthValue);
101
+ } catch (const std::exception& e) {
102
+ throw std::runtime_error("Invalid target width: " + std::string(e.what()));
103
+ }
104
+ try {
105
+ targetHeight = calcDim(inputMat.rows, heightMode, heightValue);
106
+ } catch (const std::exception& e) {
107
+ throw std::runtime_error("Invalid target height: " + std::string(e.what()));
108
+ }
71
109
 
72
110
  if (!targetWidth && !targetHeight)
73
111
  throw std::runtime_error("Both dimensions are Auto");
74
112
 
75
113
  if (!targetWidth)
76
- targetWidth = std::lround(targetHeight *
114
+ targetWidth = safeRoundToInt(targetHeight *
77
115
  (double)inputMat.cols / inputMat.rows);
78
116
  if (!targetHeight)
79
- targetHeight = std::lround(targetWidth *
117
+ targetHeight = safeRoundToInt(targetWidth *
80
118
  (double)inputMat.rows / inputMat.cols);
81
119
 
120
+ if (targetWidth <= 0 || targetHeight <= 0) {
121
+ throw std::runtime_error(
122
+ "Target dimensions must be positive (got " +
123
+ std::to_string(targetWidth) + "x" +
124
+ std::to_string(targetHeight) + ")"
125
+ );
126
+ }
127
+
128
+ // Guardrail against pathological allocations (misconfig values can overflow to huge sizes).
129
+ // Default: 4 GiB max output buffer; override via ROSEPETAL_MAX_RESIZE_BYTES.
130
+ static const uint64_t maxResizeBytes = []() -> uint64_t {
131
+ const char* env = std::getenv("ROSEPETAL_MAX_RESIZE_BYTES");
132
+ if (!env || !*env) {
133
+ return 4ULL * 1024ULL * 1024ULL * 1024ULL;
134
+ }
135
+ try {
136
+ const unsigned long long parsed = std::stoull(env);
137
+ return parsed > 0 ? static_cast<uint64_t>(parsed)
138
+ : 4ULL * 1024ULL * 1024ULL * 1024ULL;
139
+ } catch (...) {
140
+ return 4ULL * 1024ULL * 1024ULL * 1024ULL;
141
+ }
142
+ }();
143
+
144
+ const uint64_t outPixels = static_cast<uint64_t>(targetWidth) * static_cast<uint64_t>(targetHeight);
145
+ const uint64_t outBytes = outPixels * static_cast<uint64_t>(inputMat.elemSize());
146
+ if (outBytes > maxResizeBytes) {
147
+ throw std::runtime_error(
148
+ "Resize to " + std::to_string(targetWidth) + "x" + std::to_string(targetHeight) +
149
+ " would allocate too much memory (" + std::to_string(outBytes) + " bytes). " +
150
+ "Check width/height values or increase ROSEPETAL_MAX_RESIZE_BYTES."
151
+ );
152
+ }
153
+
82
154
  // --- 4.2 Redimensionar ----------------------------------------
83
155
  auto t0 = std::chrono::steady_clock::now();
84
- cv::resize(inputMat, resultMat,
85
- cv::Size(targetWidth, targetHeight),
86
- 0, 0, cv::INTER_LINEAR);
156
+ try {
157
+ cv::resize(inputMat, resultMat,
158
+ cv::Size(targetWidth, targetHeight),
159
+ 0, 0, cv::INTER_LINEAR);
160
+ } catch (const cv::Exception& e) {
161
+ const auto inStep = static_cast<unsigned long long>(inputMat.step);
162
+ const auto inElemSize = static_cast<unsigned long long>(inputMat.elemSize());
163
+ throw std::runtime_error(
164
+ std::string("cv::resize failed for ") +
165
+ std::to_string(inputMat.cols) + "x" + std::to_string(inputMat.rows) +
166
+ " type=" + std::to_string(inputMat.type()) +
167
+ " channels=" + std::to_string(inputMat.channels()) +
168
+ " elemSize=" + std::to_string(inElemSize) +
169
+ " step=" + std::to_string(inStep) +
170
+ " -> " + std::to_string(targetWidth) + "x" + std::to_string(targetHeight) +
171
+ ": " + e.what()
172
+ );
173
+ }
87
174
  auto t1 = std::chrono::steady_clock::now();
88
175
  taskMs = std::chrono::duration<double, std::milli>(t1 - t0).count();
89
176
 
90
177
  // --- 4.3 Multi-format encoding -----------------------------
91
178
  if (outputFormat != "raw") {
92
- // Convert to BGR if needed for encoding
93
- const cv::Mat& srcForEncoding =
94
- (channelOrder == "BGR") ? resultMat
95
- : ToBgrForJpg(resultMat, channelOrder);
96
-
179
+ const cv::Mat srcForEncoding =
180
+ PrepareForEncoding(resultMat, channelOrder, outputFormat);
97
181
  encodeMs = EncodeToFormat(srcForEncoding, encodedBuf, outputFormat, quality, pngOptimize);
98
182
  }
99
183
  } catch (const std::exception& e) {
@@ -110,13 +194,7 @@ protected:
110
194
 
111
195
  // --- Lógica de la Imagen ---
112
196
  if (outputFormat != "raw") {
113
- // Return encoded buffer (JPG/PNG/WebP)
114
- uint8_t* encodedData = new uint8_t[encodedBuf.size()];
115
- std::memcpy(encodedData, encodedBuf.data(), encodedBuf.size());
116
- imageResult = Napi::Buffer<uint8_t>::New(
117
- env, encodedData, encodedBuf.size(),
118
- [](Napi::Env, uint8_t* p){ delete[] p; }
119
- );
197
+ imageResult = VectorToBuffer(env, std::move(encodedBuf));
120
198
  } else {
121
199
  // Return raw image object using new format
122
200
  imageResult = MatToRawJS(env, resultMat, channelOrder);
@@ -88,11 +88,8 @@ protected:
88
88
 
89
89
  // Multi-format encoding
90
90
  if (outputFormat != "raw") {
91
- // Convert to BGR if needed for encoding
92
- const cv::Mat& srcForEncoding =
93
- (channelOrder == "BGR") ? resultMat
94
- : ToBgrForJpg(resultMat, channelOrder);
95
-
91
+ const cv::Mat srcForEncoding =
92
+ PrepareForEncoding(resultMat, channelOrder, outputFormat);
96
93
  encodeMs = EncodeToFormat(srcForEncoding, encodedBuf, outputFormat, quality, pngOptimize);
97
94
  }
98
95
  } catch (const std::exception& e) { SetError(e.what()); }
@@ -174,4 +171,4 @@ Napi::Value Rotate(const Napi::CallbackInfo& info)
174
171
  pngOptimize);
175
172
  worker->Queue();
176
173
  return env.Undefined();
177
- }
174
+ }
@@ -144,6 +144,34 @@ inline ImageFormat ParseImageFormat(const std::string& format) {
144
144
  return ImageFormat::RAW;
145
145
  }
146
146
 
147
+ // Convert to the correct channel order for OpenCV's encoders.
148
+ // - JPG: requires BGR (alpha is dropped)
149
+ // - PNG/WebP: support BGR/BGRA (alpha preserved for *A variants)
150
+ inline cv::Mat PrepareForEncoding(const cv::Mat& src,
151
+ const std::string& order,
152
+ const std::string& outputFormat)
153
+ {
154
+ const ImageFormat fmt = ParseImageFormat(outputFormat);
155
+ if (fmt == ImageFormat::JPG) {
156
+ return ToBgrForJpg(src, order);
157
+ }
158
+
159
+ // PNG/WebP: keep alpha when present
160
+ if (src.channels() == 1 || order == "BGR" || order == "BGRA" || order == "GRAY") {
161
+ return src;
162
+ }
163
+
164
+ cv::Mat dst;
165
+ if (order == "RGB") {
166
+ cv::cvtColor(src, dst, cv::COLOR_RGB2BGR);
167
+ } else if (order == "RGBA") {
168
+ cv::cvtColor(src, dst, cv::COLOR_RGBA2BGRA);
169
+ } else {
170
+ dst = src; // fallback (assume already in OpenCV-native order)
171
+ }
172
+ return dst;
173
+ }
174
+
147
175
  // Fast JPEG compression function
148
176
  inline double EncodeToJpgFast(const cv::Mat& src,
149
177
  std::vector<uchar>& out,
@@ -266,15 +294,25 @@ inline Napi::Object MatToRawJS(Napi::Env env,
266
294
  }
267
295
  o.Set("dtype", Napi::String::New(env, dtype));
268
296
 
269
- // Copy data
270
- size_t bytes = m.total() * m.elemSize();
271
- auto* raw = new uint8_t[bytes];
272
- std::memcpy(raw, m.data, bytes);
297
+ // Zero-copy where possible:
298
+ // - If Mat isn't continuous (ROI/step) or doesn't own its data (external ptr),
299
+ // clone to a contiguous owned buffer once.
300
+ cv::Mat owned = m;
301
+ if (!owned.isContinuous() || owned.u == nullptr) {
302
+ owned = m.clone();
303
+ }
304
+
305
+ auto* heapMat = new cv::Mat(std::move(owned));
306
+ const size_t bytes = heapMat->total() * heapMat->elemSize();
273
307
 
274
308
  o.Set("data", Napi::Buffer<uint8_t>::New(
275
- env, raw, bytes,
276
- [](Napi::Env, uint8_t* p) { delete[] p; }));
277
-
309
+ env,
310
+ heapMat->data,
311
+ bytes,
312
+ [](Napi::Env, uint8_t*, cv::Mat* mat) { delete mat; },
313
+ heapMat
314
+ ));
315
+
278
316
  return o;
279
317
  }
280
318
 
@@ -560,4 +598,4 @@ inline cv::Scalar parseColorString(const std::string& colorStr) {
560
598
  return cv::Scalar(255, 255, 255);
561
599
  }
562
600
 
563
- #endif // UTILS_H
601
+ #endif // UTILS_H
@@ -1,119 +0,0 @@
1
- # Array-In Node
2
-
3
- ## Purpose & Use Cases
4
-
5
- The `array-in` node collects data from various sources and tags it with position information for ordered array assembly. It works in partnership with the `array-out` node to create structured arrays from multiple parallel data streams.
6
-
7
- **Real-World Applications:**
8
- - **Batch Image Processing**: Collect multiple images for simultaneous processing
9
- - **Data Aggregation**: Combine results from parallel processing pipelines
10
- - **Multi-Source Analysis**: Merge data from different sensors or inputs
11
- - **Synchronized Processing**: Ensure data maintains order through parallel workflows
12
- - **Multi-Camera Systems**: Collect images from multiple cameras in correct sequence
13
-
14
- ![Array-In Demo](../../../assets/nodes/io/array-in-demo.gif)
15
-
16
- ## Input/Output Specification
17
-
18
- ### Inputs
19
- - **Input Message**: Message containing data at the configured input path
20
- - **Dynamic Position**: Array position can be resolved from message properties
21
-
22
- ### Outputs
23
- The node adds metadata to the message and mirrors the extracted data into the payload only when reading from `msg.payload`. For other input paths, the existing payload remains untouched while the metadata provides access to the collected value:
24
-
25
- ```javascript
26
- {
27
- ...originalMessage,
28
- payload: any, // Unchanged unless input is msg.payload; when mirrored matches meta.arrayData
29
- meta: {
30
- arrayPosition: number, // Index where this data belongs in array
31
- arrayData: any // The extracted data from input path
32
- }
33
- }
34
- ```
35
-
36
- ## Configuration Options
37
-
38
- ### Input From
39
- - **Default**: `msg.payload`
40
- - **Options**:
41
- - `msg.*` - Read from message property
42
- - `flow.*` - Read from flow context
43
- - `global.*` - Read from global context
44
- - **Purpose**: Specifies where to extract the data to be included in the array
45
-
46
- ### Array Position
47
- - **Type**: Number or dynamic reference
48
- - **Options**:
49
- - **Fixed Number**: Static position (0, 1, 2, ...)
50
- - **msg.***: Dynamic position from message property
51
- - **flow.***: Position from flow context
52
- - **global.***: Position from global context
53
- - **Range**: Non-negative integers (0-based indexing)
54
- - **Purpose**: Determines where this data appears in the final array
55
-
56
- ## Performance Notes
57
-
58
- ### Array Assembly Strategy
59
- - **Position Tagging**: Lightweight metadata addition with minimal processing overhead
60
- - **Memory Efficient**: Only stores references and position information
61
- - **Parallel Collection**: Multiple array-in nodes can operate simultaneously
62
- - **Order Preservation**: Maintains correct data sequence regardless of processing timing
63
-
64
- ### Status Display
65
- - **Processing Info**: Shows array position and data type
66
- - **Validation**: Indicates successful data extraction
67
- - **Error Handling**: Displays warnings for missing data or invalid positions
68
-
69
- ## Real-World Examples
70
-
71
- ### Basic Multi-Image Collection
72
- ```
73
- [Image-In: photo1.jpg] → [Array-In: pos=0] ┐
74
- [Image-In: photo2.jpg] → [Array-In: pos=1] ├→ [Array-Out] → [Resize All]
75
- [Image-In: photo3.jpg] → [Array-In: pos=2] ┘
76
- ```
77
- Collect three images into an ordered array for batch processing.
78
-
79
- ### Dynamic Position Assignment
80
- ```
81
- [Process Data] → [Set msg.index] → [Array-In: pos=msg.index] → [Array-Out]
82
- ```
83
- Use dynamic positioning based on processing results.
84
-
85
- ### Mixed Data Sources
86
- ```
87
- [msg.image1] → [Array-In: pos=0] ┐
88
- [flow.image2] → [Array-In: pos=1] ├→ [Array-Out] → [Concat Images]
89
- [global.image3] → [Array-In: pos=2] ┘
90
- ```
91
- Combine data from different context levels.
92
-
93
- ### Conditional Assembly
94
- ```
95
- [Switch] → [Array-In: pos=flow.nextIndex] → [Array-Out]
96
- ```
97
- Dynamic array building based on conditions.
98
-
99
- ## Common Issues & Troubleshooting
100
-
101
- ### Position Conflicts
102
- - **Issue**: Multiple nodes using same position
103
- - **Solution**: Ensure each array-in node has unique position when feeding same array-out
104
- - **Best Practice**: Use sequential positions starting from 0
105
-
106
- ### Missing Data
107
- - **Issue**: Input path contains no data
108
- - **Result**: `meta.arrayData` set to `null`
109
- - **Solution**: Verify data exists at specified input path before processing
110
-
111
- ### Dynamic Position Errors
112
- - **Issue**: Position resolves to non-integer or negative value
113
- - **Solution**: Validate dynamic position sources return valid array indices
114
- - **Check**: Use debug node to verify position values
115
-
116
- ### Array Gaps
117
- - **Issue**: Non-sequential positions create sparse arrays
118
- - **Result**: Array contains undefined elements at missing positions
119
- - **Solution**: Use sequential positions or handle sparse arrays in downstream nodes
@@ -1,150 +0,0 @@
1
- # Array-Out Node
2
-
3
- ## Purpose & Use Cases
4
-
5
- The `array-out` node serves as the collection point for multiple `array-in` nodes, assembling ordered arrays from parallel data streams. It provides timeout protection and ensures data integrity during the assembly process.
6
-
7
- **Real-World Applications:**
8
- - **Batch Image Processing**: Assemble multiple images for simultaneous operations
9
- - **Multi-Camera Synchronization**: Collect frames from multiple cameras in sequence
10
- - **Parallel Pipeline Merging**: Combine results from parallel processing workflows
11
- - **Data Aggregation**: Merge processed data from multiple sources
12
- - **Quality Control**: Collect inspection results from multiple checkpoints
13
-
14
- ![Array-Out Demo](../../../assets/nodes/io/array-out-demo.gif)
15
-
16
- ## Input/Output Specification
17
-
18
- ### Inputs
19
- Messages from `array-in` nodes containing:
20
- ```javascript
21
- {
22
- ...originalMessage,
23
- payload: any, // Fallback data source
24
- meta: {
25
- arrayPosition: number, // Position index (0, 1, 2, ...)
26
- arrayData: any // Preferred data source (takes priority over payload)
27
- }
28
- }
29
- ```
30
-
31
- **Data Extraction Priority**: The node prefers `msg.meta.arrayData` but falls back to `msg.payload` if arrayData is undefined.
32
-
33
- ### Outputs
34
-
35
- #### Output 1 - Complete Array (Success)
36
- ```javascript
37
- [data0, data1, data2, ...] // Ordered array of collected data
38
- ```
39
-
40
- #### Output 2 - Timeout Data (Error)
41
- ```javascript
42
- {
43
- [outputPath]: [data0, null, data2, ...], // Partial array in configured location
44
- meta: {
45
- timeout: true, // Timeout flag
46
- missingPositions: [1, 4], // Positions that didn't arrive
47
- collectedPositions: [0, 2, 3], // Positions that were collected
48
- expectedCount: 5, // Number expected
49
- collectedCount: 3, // Number actually collected
50
- elapsed: 5000 // Time elapsed in milliseconds
51
- }
52
- }
53
- ```
54
-
55
- ## Configuration Options
56
-
57
- ### Expected Count
58
- - **Type**: Number (required)
59
- - **Range**: Minimum 1
60
- - **Purpose**: Number of array elements required before output
61
- - **Validation**: Must match the number of connected array-in nodes
62
- - **Impact**: Array assembly completes when this many elements are collected
63
-
64
- ### Timeout
65
- - **Type**: Number (milliseconds)
66
- - **Default**: 5000ms (5 seconds)
67
- - **Range**: Minimum 100ms
68
- - **Purpose**: Maximum wait time for all elements after first message
69
- - **Behavior**: Sends partial data to output 2 on timeout
70
-
71
- ### Output Location
72
- - **Default**: `msg.payload`
73
- - **Options**:
74
- - `msg.*` - Store in message property
75
- - `flow.*` - Store in flow context
76
- - `global.*` - Store in global context
77
- - **Purpose**: Where to store the assembled array
78
-
79
- ## Performance Notes
80
-
81
- ### Assembly Strategy
82
- - **Efficient Collection**: Uses position-based indexing for O(1) insertion
83
- - **Memory Management**: Minimal overhead during collection
84
- - **Timeout Protection**: Prevents indefinite waiting for missing data
85
- - **State Reset**: Automatic cleanup between collection cycles
86
-
87
- ### Status Display
88
- - **Collection Progress**: Shows number of items collected vs expected
89
- - **Success Timing**: Displays total assembly time on completion
90
- - **Timeout Warning**: Indicates when timeout occurs with diagnostic info
91
-
92
- ## Real-World Examples
93
-
94
- ### Basic Image Array Assembly
95
- ```
96
- [Image-In: img1.jpg] → [Array-In: pos=0] ┐
97
- [Image-In: img2.jpg] → [Array-In: pos=1] ├→ [Array-Out: count=3, timeout=500] → [Resize: All Images]
98
- [Image-In: img3.jpg] → [Array-In: pos=2] ┘
99
- ```
100
- Collect three images for batch resizing.
101
-
102
- ### Multi-Camera Frame Collection
103
- ```
104
- [Camera 1] → [Array-In: pos=0] ┐
105
- [Camera 2] → [Array-In: pos=1] ├→ [Array-Out: count=4, timeout=100] → [Sync Analysis]
106
- [Camera 3] → [Array-In: pos=2] │
107
- [Camera 4] → [Array-In: pos=3] ┘
108
- ```
109
- Synchronize frames from multiple cameras with tight timing.
110
-
111
- ### Parallel Processing Merge
112
- ```
113
- → [Process A] → [Array-In: pos=0] ┐
114
- → [Process B] → [Array-In: pos=1] ├→ [Array-Out: count=3, timeout=500] → [Combine Results]
115
- → [Process C] → [Array-In: pos=2] ┘
116
- ```
117
- Merge results from parallel processing pipelines.
118
-
119
- ### Quality Control Assembly
120
- ```
121
- [Inspection A] → [Array-In: pos=0] ┐
122
- [Inspection B] → [Array-In: pos=1] ├→ [Array-Out: timeout=10000] → [Final Report]
123
- [Inspection C] → [Array-In: pos=2] ┘
124
- ```
125
- Collect quality control results with extended timeout.
126
-
127
- ## Common Issues & Troubleshooting
128
-
129
- ### Timeout Issues
130
- - **Issue**: Frequent timeouts preventing array completion
131
- - **Causes**: Slow upstream processing, network delays, missing data
132
- - **Solutions**:
133
- - Increase timeout value for slow processes
134
- - Add debug nodes to identify bottlenecks
135
- - Implement fallback logic using output 2
136
-
137
- ### Count Mismatch
138
- - **Issue**: Expected count doesn't match number of array-in nodes
139
- - **Result**: Perpetual waiting or premature completion
140
- - **Solution**: Verify expected count equals number of connected array-in nodes
141
-
142
- ### Position Conflicts
143
- - **Issue**: Multiple array-in nodes using same position
144
- - **Result**: Data overwrites, array count confusion
145
- - **Solution**: Ensure each array-in node has unique position
146
-
147
- ### Missing Metadata
148
- - **Issue**: Messages arriving without proper meta.arrayPosition
149
- - **Result**: Messages ignored, incomplete arrays
150
- - **Solution**: Verify all input messages come from array-in nodes
@@ -1,157 +0,0 @@
1
- # Array-Select Node
2
-
3
- ## Purpose & Use Cases
4
-
5
- The `array-select` node provides powerful array element selection with Python-like slicing syntax. It extracts specific elements, ranges, or patterns from arrays, making it essential for filtering and selecting processed results.
6
-
7
- **Real-World Applications:**
8
- - **Result Filtering**: Select best results from batch processing operations
9
- - **Data Sampling**: Extract samples from large datasets for analysis
10
- - **Quality Control**: Pick specific items that passed validation
11
- - **A/B Testing**: Select specific variants for comparison
12
- - **Image Gallery Creation**: Choose specific images from collections
13
-
14
- ![Array-Select Demo](../../../assets/nodes/io/array-select-demo.gif)
15
-
16
- ## Input/Output Specification
17
-
18
- ### Inputs
19
- - **Array Data**: Input array from the configured path
20
- - **Selection String**: Pattern specifying which elements to extract
21
-
22
- ### Outputs
23
- - **Single Element**: Direct element output (unless Force Array enabled)
24
- - **Multiple Elements**: Always output as array
25
- - **Invalid Selection**: No message sent, warning logged
26
-
27
- ## Configuration Options
28
-
29
- ### Input From
30
- - **Default**: `msg.payload`
31
- - **Options**:
32
- - `msg.*` - Read from message property
33
- - `flow.*` - Read from flow context
34
- - `global.*` - Read from global context
35
- - **Validation**: Input must be an array
36
-
37
- ### Selection Pattern
38
- - **Type**: String with flexible syntax
39
- - **Formats**:
40
- - **Single Index**: `0`, `2`, `-1`
41
- - **Multiple Indices**: `1,3,5` (comma-separated)
42
- - **Range**: `1:4` (slice from index 1 to 3)
43
- - **Step Pattern**: `0::2` (every 2nd element)
44
- - **Negative Indexing**: `-1` (last), `-2:` (last two)
45
-
46
- ### Force Array
47
- - **Type**: Boolean checkbox
48
- - **Default**: false
49
- - **Behavior**: When enabled, single elements output as arrays
50
- - **Use Case**: Ensure consistent array output format
51
-
52
- ## Performance Notes
53
-
54
- ### Selection Efficiency
55
- - **Minimal Memory Copy**: Efficient element extraction without full array duplication
56
- - **Index Validation**: Fast bounds checking with graceful error handling
57
- - **Pattern Parsing**: Optimized pattern recognition and processing
58
- - **Status Display**: Real-time selection information and processing state
59
-
60
- ### Error Handling
61
- - **Input Validation**: Comprehensive array and pattern validation
62
- - **Graceful Degradation**: Invalid indices skipped with warnings
63
- - **Bounds Checking**: Out-of-range indices handled safely
64
-
65
- ## Selection Syntax Guide
66
-
67
- ### Basic Selection
68
- ```
69
- Array: ["A", "B", "C", "D", "E"]
70
-
71
- 0 → "A" // First element
72
- -1 → "E" // Last element
73
- 1,3 → ["B", "D"] // Multiple specific indices
74
- ```
75
-
76
- ### Range Selection
77
- ```
78
- Array: ["A", "B", "C", "D", "E"]
79
-
80
- 1:4 → ["B", "C", "D"] // Range from 1 to 3
81
- 0:3 → ["A", "B", "C"] // First three elements
82
- -2: → ["D", "E"] // Last two elements
83
- ```
84
-
85
- ### Step Patterns
86
- ```
87
- Array: ["A", "B", "C", "D", "E", "F"]
88
-
89
- 0::2 → ["A", "C", "E"] // Every 2nd starting at 0
90
- 1::2 → ["B", "D", "F"] // Every 2nd starting at 1
91
- 1:5:2 → ["B", "D"] // Range 1-4, every 2nd
92
- ```
93
-
94
- ### Advanced Patterns
95
- ```
96
- Array: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
97
-
98
- ::3 → [0, 3, 6, 9] // Every 3rd element
99
- 2:8:2 → [2, 4, 6] // Range 2-7, step 2
100
- -3: → [7, 8, 9] // Last 3 elements
101
- :-3 → [0, 1, 2, 3, 4, 5, 6] // All but last 3
102
- ```
103
-
104
- ## Real-World Examples
105
-
106
- ### Best Result Selection
107
- ```
108
- [Batch Process] → [Array-Out] → [Array-Select: "0,2,4"] → [Top Results]
109
- ```
110
- Select 1st, 3rd, and 5th results from batch processing.
111
-
112
- ### Quality Control Sampling
113
- ```
114
- [Production Line] → [Array-Out] → [Array-Select: "::10"] → [Quality Check]
115
- ```
116
- Sample every 10th item for quality inspection.
117
-
118
- ### Image Gallery Creation
119
- ```
120
- [Image Array] → [Array-Select: "1:6"] → [Display Gallery]
121
- ```
122
- Select images 2-6 for gallery display.
123
-
124
- ### A/B Test Splitting
125
- ```
126
- [User Array] → [Array-Select: "0::2"] → [Group A]
127
- → [Array-Select: "1::2"] → [Group B]
128
- ```
129
- Split users into alternating test groups.
130
-
131
- ### Last N Results
132
- ```
133
- [Processing Queue] → [Array-Out] → [Array-Select: "-5:"] → [Recent Results]
134
- ```
135
- Get the last 5 processed items.
136
-
137
- ## Common Issues & Troubleshooting
138
-
139
- ### Invalid Input Type
140
- - **Issue**: Input is not an array
141
- - **Result**: Warning logged, message not sent
142
- - **Solution**: Verify input is array type, use array-out to create arrays
143
-
144
- ### Out of Bounds Indices
145
- - **Issue**: Selection indices exceed array length
146
- - **Result**: Invalid indices ignored, partial results returned
147
- - **Example**: Array length 5, selection "1,3,7" returns elements at indices 1,3 only
148
-
149
- ### Empty Selection Results
150
- - **Issue**: Selection pattern matches no elements
151
- - **Result**: Empty array `[]` output
152
- - **Common Cause**: Range beyond array bounds
153
-
154
- ### Syntax Errors
155
- - **Issue**: Invalid selection pattern syntax
156
- - **Result**: Warning logged, message not sent
157
- - **Solution**: Verify pattern follows documented syntax