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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import math
5
+ from typing import Any
6
+
7
+ import torch
8
+
9
+
10
+ # ---------------------------
11
+ # Helpers
12
+ # ---------------------------
13
+
14
+ def _safe_float(value: Any, default: float = 0.0) -> float:
15
+ try:
16
+ if isinstance(value, torch.Tensor):
17
+ if value.numel() > 0:
18
+ return float(value.detach().cpu().reshape(-1)[0])
19
+ return float(default)
20
+ return float(value)
21
+ except Exception:
22
+ return float(default)
23
+
24
+
25
+ def _clean_label(label: Any) -> str:
26
+ """
27
+ Clean labels so the returned names string stays parseable:
28
+ [0:car], [1:house]
29
+ """
30
+ text = str(label if label is not None else "unknown").strip()
31
+ text = (
32
+ text.replace("\r", " ")
33
+ .replace("\n", " ")
34
+ .replace("[", "(")
35
+ .replace("]", ")")
36
+ .replace(",", ";")
37
+ )
38
+ return text or "unknown"
39
+
40
+
41
+ def _get_seg_value(seg: Any, attr_name: str, tuple_index: int, default: Any = None) -> Any:
42
+ """
43
+ Supports both namedtuple/object-style SEG:
44
+ seg.label
45
+ and tuple/list-style SEG:
46
+ seg[5]
47
+ """
48
+ if hasattr(seg, attr_name):
49
+ return getattr(seg, attr_name)
50
+
51
+ if isinstance(seg, (tuple, list)) and len(seg) > tuple_index:
52
+ return seg[tuple_index]
53
+
54
+ return default
55
+
56
+
57
+ def _normalize_bbox_xyxy(bbox: Any, image_w: int, image_h: int) -> tuple[int, int, int, int] | None:
58
+ """
59
+ Converts bbox-like values to clamped integer xyxy coordinates.
60
+ """
61
+ try:
62
+ if isinstance(bbox, torch.Tensor):
63
+ bbox = bbox.detach().cpu().reshape(-1).tolist()
64
+
65
+ x1f, y1f, x2f, y2f = [float(v) for v in bbox[:4]]
66
+ except Exception:
67
+ return None
68
+
69
+ left = int(math.floor(min(x1f, x2f)))
70
+ top = int(math.floor(min(y1f, y2f)))
71
+ right = int(math.ceil(max(x1f, x2f)))
72
+ bottom = int(math.ceil(max(y1f, y2f)))
73
+
74
+ left = max(0, min(image_w, left))
75
+ top = max(0, min(image_h, top))
76
+ right = max(0, min(image_w, right))
77
+ bottom = max(0, min(image_h, bottom))
78
+
79
+ if right <= left or bottom <= top:
80
+ return None
81
+
82
+ return left, top, right, bottom
83
+
84
+
85
+ def _normalize_crop_tensor(crop: Any) -> torch.Tensor | None:
86
+ """
87
+ Normalizes a crop into ComfyUI IMAGE batch format:
88
+ [1, H, W, C]
89
+ """
90
+ if not isinstance(crop, torch.Tensor):
91
+ return None
92
+
93
+ if crop.dim() == 3:
94
+ crop = crop.unsqueeze(0)
95
+
96
+ if crop.dim() != 4:
97
+ return None
98
+
99
+ if crop.shape[0] > 1:
100
+ crop = crop[0:1]
101
+
102
+ if crop.shape[1] <= 0 or crop.shape[2] <= 0:
103
+ return None
104
+
105
+ if crop.shape[-1] == 1:
106
+ crop = crop.repeat(1, 1, 1, 3)
107
+
108
+ return crop.clamp(0.0, 1.0)
109
+
110
+
111
+ def _crop_image_xyxy(image_one: torch.Tensor, bbox_xyxy: tuple[int, int, int, int]) -> torch.Tensor | None:
112
+ """
113
+ Crops one ComfyUI IMAGE tensor.
114
+ image_one must be [1, H, W, C].
115
+ """
116
+ x1, y1, x2, y2 = bbox_xyxy
117
+ return _normalize_crop_tensor(image_one[:, y1:y2, x1:x2, :])
118
+
119
+
120
+ def _blank_image_like(image: Any, mode: str) -> torch.Tensor:
121
+ """
122
+ ComfyUI IMAGE outputs are safest when they contain at least one image.
123
+ Used when no bboxes are found or the detector fails.
124
+ """
125
+ dtype = torch.float32
126
+ device = "cpu"
127
+ h = 64
128
+ w = 64
129
+ c = 3
130
+
131
+ if isinstance(image, torch.Tensor):
132
+ dtype = image.dtype
133
+ device = image.device
134
+
135
+ if image.dim() == 4:
136
+ h = int(image.shape[1])
137
+ w = int(image.shape[2])
138
+ c = int(image.shape[3])
139
+ elif image.dim() == 3:
140
+ h = int(image.shape[0])
141
+ w = int(image.shape[1])
142
+ c = int(image.shape[2])
143
+
144
+ if mode == "input_image" and isinstance(image, torch.Tensor):
145
+ if image.dim() == 4:
146
+ return image[0:1].clone().clamp(0.0, 1.0)
147
+ if image.dim() == 3:
148
+ return image.unsqueeze(0).clone().clamp(0.0, 1.0)
149
+
150
+ if mode == "black_same_size":
151
+ out_h = max(1, h)
152
+ out_w = max(1, w)
153
+ elif mode == "black_1x1":
154
+ out_h = 1
155
+ out_w = 1
156
+ else:
157
+ out_h = 64
158
+ out_w = 64
159
+
160
+ return torch.zeros((1, out_h, out_w, max(1, c)), dtype=dtype, device=device)
161
+
162
+
163
+ def _pad_image_nhwc(crop: torch.Tensor, target_h: int, target_w: int, pad_value: float) -> torch.Tensor:
164
+ """
165
+ Pads a [1, H, W, C] crop to [1, target_h, target_w, C].
166
+ The crop is centered. Aspect ratio and original crop pixels are preserved.
167
+ """
168
+ b, h, w, c = crop.shape
169
+
170
+ target_h = max(int(target_h), int(h))
171
+ target_w = max(int(target_w), int(w))
172
+
173
+ out = crop.new_full((b, target_h, target_w, c), float(pad_value))
174
+
175
+ y = (target_h - int(h)) // 2
176
+ x = (target_w - int(w)) // 2
177
+
178
+ out[:, y:y + h, x:x + w, :] = crop
179
+ return out.clamp(0.0, 1.0)
180
+
181
+
182
+ def _resize_image_nhwc(crop: torch.Tensor, target_h: int, target_w: int) -> torch.Tensor:
183
+ """
184
+ Resizes a [1, H, W, C] crop to [1, target_h, target_w, C].
185
+ """
186
+ target_h = max(1, int(target_h))
187
+ target_w = max(1, int(target_w))
188
+
189
+ original_dtype = crop.dtype
190
+ work = crop
191
+
192
+ if not torch.is_floating_point(work):
193
+ work = work.float()
194
+
195
+ work = work.permute(0, 3, 1, 2)
196
+
197
+ resized = torch.nn.functional.interpolate(
198
+ work,
199
+ size=(target_h, target_w),
200
+ mode="bilinear",
201
+ align_corners=False,
202
+ )
203
+
204
+ resized = resized.permute(0, 2, 3, 1).clamp(0.0, 1.0)
205
+ return resized.to(dtype=original_dtype)
206
+
207
+
208
+ def _call_bbox_detector(
209
+ bbox_detector: Any,
210
+ image_one: torch.Tensor,
211
+ threshold: float,
212
+ dilation: int,
213
+ crop_factor: float,
214
+ drop_size: int,
215
+ ):
216
+ """
217
+ Calls common Impact-compatible BBOX_DETECTOR signatures.
218
+
219
+ Expected return:
220
+ ((height, width), [SEG, SEG, ...])
221
+ """
222
+ try:
223
+ return bbox_detector.detect(
224
+ image_one,
225
+ float(threshold),
226
+ int(dilation),
227
+ float(crop_factor),
228
+ int(drop_size),
229
+ )
230
+ except TypeError:
231
+ return bbox_detector.detect(
232
+ image_one,
233
+ float(threshold),
234
+ int(dilation),
235
+ float(crop_factor),
236
+ )
237
+
238
+
239
+ # ---------------------------
240
+ # ComfyUI Node
241
+ # ---------------------------
242
+
243
+ class Salia_BBox_to_IMG_2:
244
+ """
245
+ Standalone node.
246
+
247
+ Input:
248
+ BBOX_DETECTOR
249
+ IMAGE
250
+
251
+ Output:
252
+ IMAGE batch of all detected bbox crops
253
+ STRING names: [0:car], [1:car], [2:house]
254
+ STRING info
255
+ STRING status
256
+ """
257
+
258
+ CATEGORY = "Salia/Detectors"
259
+ FUNCTION = "doit"
260
+
261
+ RETURN_TYPES = ("IMAGE", "STRING", "STRING", "STRING")
262
+ RETURN_NAMES = ("bbox_images", "bbox_names", "bbox_info", "status")
263
+
264
+ DESCRIPTION = (
265
+ "Runs a BBOX_DETECTOR on an IMAGE and returns all detected bbox crops "
266
+ "as an IMAGE batch, plus bracketed label names, detailed bbox info, "
267
+ "and a status string."
268
+ )
269
+
270
+ @classmethod
271
+ def INPUT_TYPES(cls):
272
+ return {
273
+ "required": {
274
+ "bbox_detector": ("BBOX_DETECTOR",),
275
+ "image": ("IMAGE",),
276
+
277
+ "threshold": (
278
+ "FLOAT",
279
+ {
280
+ "default": 0.30,
281
+ "min": 0.0,
282
+ "max": 1.0,
283
+ "step": 0.01,
284
+ },
285
+ ),
286
+
287
+ "dilation": (
288
+ "INT",
289
+ {
290
+ "default": 0,
291
+ "min": 0,
292
+ "max": 512,
293
+ "step": 1,
294
+ },
295
+ ),
296
+
297
+ "crop_factor": (
298
+ "FLOAT",
299
+ {
300
+ "default": 1.0,
301
+ "min": 0.05,
302
+ "max": 10.0,
303
+ "step": 0.05,
304
+ },
305
+ ),
306
+
307
+ "drop_size": (
308
+ "INT",
309
+ {
310
+ "default": 1,
311
+ "min": 0,
312
+ "max": 1048576,
313
+ "step": 1,
314
+ },
315
+ ),
316
+
317
+ # 0 means unlimited.
318
+ "max_detections": (
319
+ "INT",
320
+ {
321
+ "default": 0,
322
+ "min": 0,
323
+ "max": 10000,
324
+ "step": 1,
325
+ },
326
+ ),
327
+
328
+ "sort_by": (
329
+ [
330
+ "confidence_desc",
331
+ "input_order",
332
+ "left_to_right",
333
+ "top_to_bottom",
334
+ "area_desc",
335
+ ],
336
+ ),
337
+
338
+ # ComfyUI IMAGE batches need one shared H/W.
339
+ # pad_to_largest preserves crop scale.
340
+ # resize_fixed forces all crops to output_width/output_height.
341
+ "batch_mode": (
342
+ [
343
+ "pad_to_largest",
344
+ "resize_fixed",
345
+ ],
346
+ ),
347
+
348
+ # Used only when batch_mode == resize_fixed.
349
+ "output_width": (
350
+ "INT",
351
+ {
352
+ "default": 512,
353
+ "min": 1,
354
+ "max": 16384,
355
+ "step": 1,
356
+ },
357
+ ),
358
+
359
+ "output_height": (
360
+ "INT",
361
+ {
362
+ "default": 512,
363
+ "min": 1,
364
+ "max": 16384,
365
+ "step": 1,
366
+ },
367
+ ),
368
+
369
+ # Used only when batch_mode == pad_to_largest.
370
+ "pad_value": (
371
+ "FLOAT",
372
+ {
373
+ "default": 0.0,
374
+ "min": 0.0,
375
+ "max": 1.0,
376
+ "step": 0.01,
377
+ },
378
+ ),
379
+
380
+ # Output image when nothing was found.
381
+ "empty_image_mode": (
382
+ [
383
+ "black_64",
384
+ "black_1x1",
385
+ "black_same_size",
386
+ "input_image",
387
+ ],
388
+ ),
389
+ }
390
+ }
391
+
392
+ def doit(
393
+ self,
394
+ bbox_detector,
395
+ image,
396
+ threshold,
397
+ dilation,
398
+ crop_factor,
399
+ drop_size,
400
+ max_detections,
401
+ sort_by,
402
+ batch_mode,
403
+ output_width,
404
+ output_height,
405
+ pad_value,
406
+ empty_image_mode,
407
+ ):
408
+ if bbox_detector is None or not hasattr(bbox_detector, "detect"):
409
+ return (
410
+ _blank_image_like(image, empty_image_mode),
411
+ "",
412
+ "detections=0",
413
+ "error: bbox_detector is missing or does not provide detect(...)",
414
+ )
415
+
416
+ if not isinstance(image, torch.Tensor) or image.dim() not in (3, 4):
417
+ return (
418
+ _blank_image_like(image, empty_image_mode),
419
+ "",
420
+ "detections=0",
421
+ f"error: expected IMAGE tensor with 3 or 4 dims, got {type(image)}",
422
+ )
423
+
424
+ image_batch = image if image.dim() == 4 else image.unsqueeze(0)
425
+
426
+ detections: list[dict[str, Any]] = []
427
+ errors: list[str] = []
428
+ order = 0
429
+
430
+ for source_index in range(int(image_batch.shape[0])):
431
+ image_one = image_batch[source_index:source_index + 1]
432
+
433
+ image_h = int(image_one.shape[1])
434
+ image_w = int(image_one.shape[2])
435
+
436
+ try:
437
+ segs = _call_bbox_detector(
438
+ bbox_detector=bbox_detector,
439
+ image_one=image_one,
440
+ threshold=float(threshold),
441
+ dilation=int(dilation),
442
+ crop_factor=float(crop_factor),
443
+ drop_size=int(drop_size),
444
+ )
445
+ except Exception as e:
446
+ message = f"source={source_index}: detector failed: {e}"
447
+ errors.append(message)
448
+ logging.warning("[Salia BBox Crops Batch Only] %s", message)
449
+ continue
450
+
451
+ if not isinstance(segs, tuple) or len(segs) < 2:
452
+ errors.append(f"source={source_index}: detector returned unexpected output")
453
+ continue
454
+
455
+ items = segs[1]
456
+
457
+ if not isinstance(items, (list, tuple)):
458
+ errors.append(f"source={source_index}: detector output has no SEG list")
459
+ continue
460
+
461
+ for item in items:
462
+ label = _clean_label(_get_seg_value(item, "label", 5, "unknown"))
463
+ confidence = _safe_float(_get_seg_value(item, "confidence", 2, 0.0), 0.0)
464
+
465
+ raw_bbox = _get_seg_value(item, "bbox", 4, None)
466
+ bbox_xyxy = (
467
+ _normalize_bbox_xyxy(raw_bbox, image_w, image_h)
468
+ if raw_bbox is not None
469
+ else None
470
+ )
471
+
472
+ crop = _normalize_crop_tensor(_get_seg_value(item, "cropped_image", 0, None))
473
+
474
+ # Fallback for detectors that return bbox but no cropped image.
475
+ if crop is None and bbox_xyxy is not None:
476
+ crop = _crop_image_xyxy(image_one, bbox_xyxy)
477
+
478
+ if crop is None:
479
+ errors.append(f"source={source_index}: skipped detection with no valid crop")
480
+ continue
481
+
482
+ crop_h = int(crop.shape[1])
483
+ crop_w = int(crop.shape[2])
484
+
485
+ area = 0
486
+ if bbox_xyxy is not None:
487
+ x1, y1, x2, y2 = bbox_xyxy
488
+ area = max(0, x2 - x1) * max(0, y2 - y1)
489
+
490
+ detections.append(
491
+ {
492
+ "source_index": int(source_index),
493
+ "order": int(order),
494
+ "label": label,
495
+ "confidence": float(confidence),
496
+ "bbox": bbox_xyxy,
497
+ "crop": crop,
498
+ "crop_h": crop_h,
499
+ "crop_w": crop_w,
500
+ "area": int(area),
501
+ }
502
+ )
503
+
504
+ order += 1
505
+
506
+ if not detections:
507
+ info = (
508
+ f"detections=0; "
509
+ f"source_images={int(image_batch.shape[0])}; "
510
+ f"threshold={float(threshold):.3f}"
511
+ )
512
+
513
+ if errors:
514
+ info += "; errors=" + " | ".join(errors[:5])
515
+ status = "error: detector produced no usable bboxes; " + " | ".join(errors[:2])
516
+ else:
517
+ status = "no bboxes found"
518
+
519
+ return (
520
+ _blank_image_like(image, empty_image_mode),
521
+ "",
522
+ info,
523
+ status,
524
+ )
525
+
526
+ if sort_by == "confidence_desc":
527
+ detections.sort(key=lambda d: (-d["confidence"], d["order"]))
528
+
529
+ elif sort_by == "left_to_right":
530
+ detections.sort(
531
+ key=lambda d: (
532
+ d["source_index"],
533
+ d["bbox"][0] if d["bbox"] is not None else 0,
534
+ d["bbox"][1] if d["bbox"] is not None else 0,
535
+ d["order"],
536
+ )
537
+ )
538
+
539
+ elif sort_by == "top_to_bottom":
540
+ detections.sort(
541
+ key=lambda d: (
542
+ d["source_index"],
543
+ d["bbox"][1] if d["bbox"] is not None else 0,
544
+ d["bbox"][0] if d["bbox"] is not None else 0,
545
+ d["order"],
546
+ )
547
+ )
548
+
549
+ elif sort_by == "area_desc":
550
+ detections.sort(key=lambda d: (-d["area"], d["order"]))
551
+
552
+ else:
553
+ detections.sort(key=lambda d: d["order"])
554
+
555
+ total_detected = len(detections)
556
+
557
+ max_detections = int(max_detections)
558
+ if max_detections > 0:
559
+ detections = detections[:max_detections]
560
+
561
+ if batch_mode == "resize_fixed":
562
+ target_h = max(1, int(output_height))
563
+ target_w = max(1, int(output_width))
564
+
565
+ batch_items = [
566
+ _resize_image_nhwc(d["crop"], target_h, target_w)
567
+ for d in detections
568
+ ]
569
+
570
+ else:
571
+ target_h = max(int(d["crop"].shape[1]) for d in detections)
572
+ target_w = max(int(d["crop"].shape[2]) for d in detections)
573
+
574
+ batch_items = [
575
+ _pad_image_nhwc(
576
+ d["crop"],
577
+ target_h,
578
+ target_w,
579
+ float(pad_value),
580
+ )
581
+ for d in detections
582
+ ]
583
+
584
+ bbox_images = torch.cat(batch_items, dim=0).clamp(0.0, 1.0)
585
+
586
+ bbox_names = ", ".join(
587
+ f"[{i}:{d['label']}]" for i, d in enumerate(detections)
588
+ )
589
+
590
+ info_items = []
591
+
592
+ for i, d in enumerate(detections):
593
+ if d["bbox"] is None:
594
+ bbox_text = "unknown"
595
+ else:
596
+ x1, y1, x2, y2 = d["bbox"]
597
+ bbox_text = f"{x1},{y1},{x2},{y2}"
598
+
599
+ info_items.append(
600
+ f"[{i}] "
601
+ f"source={d['source_index']} "
602
+ f"name={d['label']} "
603
+ f"conf={d['confidence']:.4f} "
604
+ f"bbox={bbox_text} "
605
+ f"crop={d['crop_w']}x{d['crop_h']} "
606
+ f"output={target_w}x{target_h}"
607
+ )
608
+
609
+ bbox_info = "; ".join(info_items)
610
+
611
+ status = f"ok: {len(detections)} bbox(es) found"
612
+
613
+ if max_detections > 0 and total_detected > len(detections):
614
+ status += f"; limited from {total_detected} by max_detections={max_detections}"
615
+
616
+ if errors:
617
+ status += f"; warnings={len(errors)}"
618
+
619
+ return (
620
+ bbox_images,
621
+ bbox_names,
622
+ bbox_info,
623
+ status,
624
+ )
625
+
626
+
627
+ NODE_CLASS_MAPPINGS = {
628
+ "Salia_BBox_to_IMG_2": Salia_BBox_to_IMG_2,
629
+ }
630
+
631
+ NODE_DISPLAY_NAME_MAPPINGS = {
632
+ "Salia_BBox_to_IMG_2": "Salia_BBox_to_IMG_2",
633
+ }