saliacoel commited on
Commit
cfd41d9
·
verified ·
1 Parent(s): fa43fe0

Upload Get_Correct_Batch_Img.py

Browse files
Files changed (1) hide show
  1. Get_Correct_Batch_Img.py +330 -0
Get_Correct_Batch_Img.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ class Get_Correct_Batch_Img:
5
+ """
6
+ Given a batch of RGBA images, scan a given Y row across a (sub)batch and
7
+ treat the visible span width on that row as a 1D curve over time (batch index).
8
+
9
+ This node:
10
+ - Measures the visible width for EVERY image in the selected sub-batch.
11
+ - Detects a "big wave" pattern and extracts 5 checkpoints:
12
+ cp0: first major high (start-side high)
13
+ cp1: first major low (first valley)
14
+ cp2: next major high (peak after first valley)
15
+ cp3: second major low (second valley)
16
+ cp4: final major high (peak after second valley, then shifted 5% back towards cp3)
17
+ - For each consecutive checkpoint pair, also finds an "in-between" frame:
18
+ mid_0_1: width closest to midpoint between cp0 and cp1
19
+ mid_1_2: width closest to midpoint between cp1 and cp2
20
+ mid_2_3: width closest to midpoint between cp2 and cp3
21
+ mid_3_4: width closest to midpoint between cp3 and cp4
22
+
23
+ Outputs (all RGBA, B=1):
24
+ cp0_start_high
25
+ cp1_low_1
26
+ cp2_high_2
27
+ cp3_low_2
28
+ cp4_high_3
29
+ mid_0_1
30
+ mid_1_2
31
+ mid_2_3
32
+ mid_3_4
33
+
34
+ Visibility is determined from the alpha channel (A > 0). Images with no
35
+ visible pixels on that row are treated as width = 0 (completely thin).
36
+ Only images within [start_index, end_index] (inclusive) are considered.
37
+ """
38
+
39
+ CATEGORY = "image/batch"
40
+
41
+ @classmethod
42
+ def INPUT_TYPES(cls):
43
+ return {
44
+ "required": {
45
+ # RGBA image batch: torch.Tensor [B, H, W, 4]
46
+ "images": ("IMAGE",),
47
+
48
+ # Sub-batch start index (inclusive, 0-based)
49
+ "start_index": (
50
+ "INT",
51
+ {
52
+ "default": 0,
53
+ "min": 0,
54
+ "max": 2_147_483_647,
55
+ "step": 1,
56
+ },
57
+ ),
58
+
59
+ # Sub-batch end index (inclusive, 0-based)
60
+ "end_index": (
61
+ "INT",
62
+ {
63
+ "default": 0,
64
+ "min": 0,
65
+ "max": 2_147_483_647,
66
+ "step": 1,
67
+ },
68
+ ),
69
+
70
+ # Y coordinate (row) used for the horizontal scan
71
+ "y_coord": (
72
+ "INT",
73
+ {
74
+ "default": 0,
75
+ "min": 0,
76
+ "max": 2_147_483_647,
77
+ "step": 1,
78
+ },
79
+ ),
80
+ }
81
+ }
82
+
83
+ # 5 checkpoints + 4 inbetweens = 9 outputs
84
+ RETURN_TYPES = ("IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE",
85
+ "IMAGE", "IMAGE", "IMAGE", "IMAGE")
86
+ RETURN_NAMES = (
87
+ "cp0_start_high",
88
+ "cp1_low_1",
89
+ "cp2_high_2",
90
+ "cp3_low_2",
91
+ "cp4_high_3",
92
+ "mid_0_1",
93
+ "mid_1_2",
94
+ "mid_2_3",
95
+ "mid_3_4",
96
+ )
97
+ FUNCTION = "select"
98
+
99
+ def _compute_widths(self, images, start, end, y, alpha_threshold=0.0):
100
+ """
101
+ For each image in [start, end], compute the visible width on row y.
102
+ Visibility is alpha > alpha_threshold. If no visible pixels, width = 0.
103
+ Returns a Python list of widths (len = end-start+1).
104
+ """
105
+ widths = []
106
+ for i in range(start, end + 1):
107
+ row_alpha = images[i, y, :, 3]
108
+ visible = row_alpha > alpha_threshold
109
+
110
+ if torch.any(visible):
111
+ # Indices of visible pixels along X
112
+ visible_indices = torch.nonzero(visible, as_tuple=False).squeeze(1)
113
+ left_x = int(visible_indices[0])
114
+ right_x = int(visible_indices[-1])
115
+ width_px = right_x - left_x + 1 # inclusive distance
116
+ else:
117
+ # No visible pixels -> treat as width 0
118
+ width_px = 0
119
+
120
+ widths.append(float(width_px))
121
+
122
+ return widths
123
+
124
+ def _compute_checkpoints(self, widths):
125
+ """
126
+ From a list of widths (one per frame in sub-batch), compute 5 checkpoints:
127
+ cp0, cp1, cp2, cp3, cp4 (indices into `widths` list).
128
+
129
+ Strategy (global-ish, not just tiny local wiggles):
130
+ - Split sequence into two halves.
131
+ - cp1 = minimum in first half (first big valley)
132
+ - cp3 = minimum in second half (second big valley)
133
+ - cp0 = maximum from start .. cp1
134
+ - cp2 = maximum from cp1 .. cp3
135
+ - cp4 = maximum from cp3 .. end
136
+ - Then nudge cp4 5% of the distance back towards cp3.
137
+ """
138
+ n = len(widths)
139
+ if n == 0:
140
+ return [0, 0, 0, 0, 0]
141
+
142
+ # Very small sequences: just spread indices out linearly.
143
+ if n < 4:
144
+ cp0 = 0
145
+ cp4 = n - 1
146
+ cp1 = max(0, min(n - 1, n // 4))
147
+ cp3 = max(0, min(n - 1, (3 * n) // 4))
148
+ cp2 = max(cp1, min(cp3, (cp1 + cp3) // 2))
149
+ return [cp0, cp1, cp2, cp3, cp4]
150
+
151
+ # Normal case: n >= 4
152
+ mid = n // 2
153
+
154
+ # cp1: global min in the FIRST half [0 .. mid]
155
+ first_half_end = mid
156
+ cp1_rel = min(range(0, first_half_end + 1), key=lambda i: widths[i])
157
+ cp1 = cp1_rel
158
+
159
+ # cp3: global min in the SECOND half [mid .. n-1]
160
+ second_half_start = mid
161
+ cp3_rel = min(range(second_half_start, n), key=lambda i: widths[i])
162
+ cp3 = cp3_rel
163
+
164
+ # Ensure cp3 is strictly after cp1 where possible, so we genuinely get a second valley.
165
+ if cp3 <= cp1 and cp1 + 1 < n:
166
+ cp3 = min(range(cp1 + 1, n), key=lambda i: widths[i])
167
+
168
+ # cp0: highest point before (and including) cp1
169
+ cp0 = max(range(0, cp1 + 1), key=lambda i: widths[i])
170
+
171
+ # cp2: highest point between cp1 and cp3 (inclusive)
172
+ cp2 = cp1 + max(range(0, (cp3 - cp1) + 1), key=lambda k: widths[cp1 + k])
173
+
174
+ # cp4: highest point from cp3 to end
175
+ cp4 = cp3 + max(range(0, n - cp3), key=lambda k: widths[cp3 + k])
176
+
177
+ # Nudge cp4 5% towards cp3 along the index axis
178
+ if cp4 > cp3:
179
+ dist = cp4 - cp3
180
+ new_cp4_float = cp4 - 0.05 * dist
181
+ new_cp4 = int(round(new_cp4_float))
182
+ # Clamp to stay between cp3 and cp4
183
+ new_cp4 = max(cp3, min(cp4, new_cp4))
184
+ cp4 = new_cp4
185
+
186
+ return [cp0, cp1, cp2, cp3, cp4]
187
+
188
+ def _find_mid_index(self, idx_a, idx_b, widths):
189
+ """
190
+ Given two checkpoint indices and the width list, find the index whose
191
+ width is closest to the midpoint (average) of those two widths.
192
+
193
+ Prefer a TRUE in-between frame if possible (strictly between the two
194
+ indices). If there's no index in-between (they're adjacent or equal),
195
+ fall back to one of the endpoints.
196
+ """
197
+ if idx_a == idx_b:
198
+ return idx_a
199
+
200
+ if idx_a < idx_b:
201
+ lo, hi = idx_a, idx_b
202
+ else:
203
+ lo, hi = idx_b, idx_a
204
+
205
+ target = (widths[idx_a] + widths[idx_b]) / 2.0
206
+
207
+ # Strictly between indices, if any
208
+ candidates = list(range(lo + 1, hi))
209
+ if not candidates:
210
+ # No in-between frames; allow endpoints
211
+ candidates = [lo, hi]
212
+
213
+ best_idx = candidates[0]
214
+ best_diff = abs(widths[best_idx] - target)
215
+
216
+ for j in candidates[1:]:
217
+ diff = abs(widths[j] - target)
218
+ if diff < best_diff:
219
+ best_diff = diff
220
+ best_idx = j
221
+
222
+ return best_idx
223
+
224
+ def select(self, images, start_index, end_index, y_coord):
225
+ # --- Basic sanity checks on the input tensor ---
226
+ if not isinstance(images, torch.Tensor):
227
+ raise TypeError(f"Expected IMAGE tensor, got {type(images)}")
228
+
229
+ if images.ndim != 4:
230
+ raise ValueError(
231
+ f"Expected IMAGE of shape [B,H,W,C], got {tuple(images.shape)}"
232
+ )
233
+
234
+ batch_size, height, width, channels = images.shape
235
+
236
+ if channels != 4:
237
+ raise ValueError(
238
+ f"Expected RGBA image with 4 channels, got {channels}. "
239
+ "Make sure your input batch is RGBA (not RGB)."
240
+ )
241
+
242
+ if batch_size == 0:
243
+ raise ValueError("Empty image batch passed to Get_Correct_Batch_Img.")
244
+
245
+ # --- Clamp and normalize indices ---
246
+ start = max(0, min(int(start_index), batch_size - 1))
247
+ end = max(0, min(int(end_index), batch_size - 1))
248
+ if start > end:
249
+ start, end = end, start # swap so start <= end
250
+
251
+ # Clamp Y coordinate into image bounds
252
+ y = max(0, min(int(y_coord), height - 1))
253
+
254
+ # --- 1) Measure width for every image in the sub-batch ---
255
+ widths = self._compute_widths(images, start, end, y)
256
+ n = len(widths)
257
+
258
+ # Safety: if for some reason we got no widths (shouldn't happen), just
259
+ # use start as everything.
260
+ if n == 0:
261
+ base_img = images[start].unsqueeze(0)
262
+ return (
263
+ base_img, base_img, base_img, base_img, base_img,
264
+ base_img, base_img, base_img, base_img,
265
+ )
266
+
267
+ # --- 2) Find the 5 checkpoints on this "wave" ---
268
+ cp0, cp1, cp2, cp3, cp4 = self._compute_checkpoints(widths)
269
+
270
+ # Clamp checkpoints to valid local indices, just in case
271
+ cp0 = max(0, min(n - 1, int(cp0)))
272
+ cp1 = max(0, min(n - 1, int(cp1)))
273
+ cp2 = max(0, min(n - 1, int(cp2)))
274
+ cp3 = max(0, min(n - 1, int(cp3)))
275
+ cp4 = max(0, min(n - 1, int(cp4)))
276
+
277
+ # --- 3) Compute in-betweens between each consecutive pair ---
278
+ mid_0_1 = self._find_mid_index(cp0, cp1, widths)
279
+ mid_1_2 = self._find_mid_index(cp1, cp2, widths)
280
+ mid_2_3 = self._find_mid_index(cp2, cp3, widths)
281
+ mid_3_4 = self._find_mid_index(cp3, cp4, widths)
282
+
283
+ # Map local indices [0..n-1] back to global batch indices [0..batch_size-1]
284
+ def local_to_global(local_idx):
285
+ return start + local_idx
286
+
287
+ idx_cp0 = local_to_global(cp0)
288
+ idx_cp1 = local_to_global(cp1)
289
+ idx_cp2 = local_to_global(cp2)
290
+ idx_cp3 = local_to_global(cp3)
291
+ idx_cp4 = local_to_global(cp4)
292
+
293
+ idx_mid_0_1 = local_to_global(mid_0_1)
294
+ idx_mid_1_2 = local_to_global(mid_1_2)
295
+ idx_mid_2_3 = local_to_global(mid_2_3)
296
+ idx_mid_3_4 = local_to_global(mid_3_4)
297
+
298
+ # --- 4) Extract the corresponding images as individual 1-image batches ---
299
+ cp0_img = images[idx_cp0].unsqueeze(0)
300
+ cp1_img = images[idx_cp1].unsqueeze(0)
301
+ cp2_img = images[idx_cp2].unsqueeze(0)
302
+ cp3_img = images[idx_cp3].unsqueeze(0)
303
+ cp4_img = images[idx_cp4].unsqueeze(0)
304
+
305
+ mid_0_1_img = images[idx_mid_0_1].unsqueeze(0)
306
+ mid_1_2_img = images[idx_mid_1_2].unsqueeze(0)
307
+ mid_2_3_img = images[idx_mid_2_3].unsqueeze(0)
308
+ mid_3_4_img = images[idx_mid_3_4].unsqueeze(0)
309
+
310
+ return (
311
+ cp0_img,
312
+ cp1_img,
313
+ cp2_img,
314
+ cp3_img,
315
+ cp4_img,
316
+ mid_0_1_img,
317
+ mid_1_2_img,
318
+ mid_2_3_img,
319
+ mid_3_4_img,
320
+ )
321
+
322
+
323
+ # Register node with ComfyUI
324
+ NODE_CLASS_MAPPINGS = {
325
+ "Get_Correct_Batch_Img": Get_Correct_Batch_Img,
326
+ }
327
+
328
+ NODE_DISPLAY_NAME_MAPPINGS = {
329
+ "Get_Correct_Batch_Img": "Get_Correct_Batch_Img (Salia Wave)",
330
+ }