proyeksigila commited on
Commit
8ad4a65
Β·
verified Β·
1 Parent(s): 52ba0b4

Upload Occlusion.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. Occlusion.py +685 -0
Occlusion.py ADDED
@@ -0,0 +1,685 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ OcclusionMask Node for ComfyUI
3
+ -------------------------------
4
+ Purpose: Generate an occlusion protection mask for use with ReActor (and similar
5
+ faceswap nodes). The mask marks pixels that are covered by objects IN FRONT OF
6
+ the face (microphones, hands, glasses, food, etc.) so the faceswap node knows
7
+ to leave those pixels untouched.
8
+
9
+ Pipeline per face:
10
+ 1. Detect face(s) with InsightFace
11
+ 2. Crop + pad the face region, resize to 256x256
12
+ 3. Run occluder.onnx β†’ "something is in front of the face here"
13
+ 4. Run XSeg_model.onnx β†’ "this is the face skin region"
14
+ 5. Final mask = occluder_mask AND NOT xseg_face_mask
15
+ = "pixels that are occluded AND not naked face skin"
16
+ 6. Post-process: expand β†’ feather
17
+ 7. Paste mask back onto full-image canvas
18
+ 8. Repeat for every detected face, union all per-face masks
19
+
20
+ ReActor wiring:
21
+ IMAGE β†’ ReActor input_image
22
+ MASK β†’ ReActor face_mask (tells ReActor: "preserve these pixels")
23
+ PREVIEW β†’ Preview Image node (for tuning / debugging)
24
+
25
+ Author: redesigned for clarity and correctness.
26
+ """
27
+
28
+ import os
29
+ import logging
30
+ import numpy as np
31
+ from PIL import Image, ImageDraw
32
+ import torch
33
+ import cv2
34
+ import onnxruntime as ort
35
+ from insightface.app import FaceAnalysis
36
+ from .face_helpers.face_masks import FaceMasks
37
+
38
+ _logger = logging.getLogger(__name__)
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # Providers helper
42
+ # ---------------------------------------------------------------------------
43
+ def _ort_providers():
44
+ return (
45
+ ["CUDAExecutionProvider", "CPUExecutionProvider"]
46
+ if torch.cuda.is_available()
47
+ else ["CPUExecutionProvider"]
48
+ )
49
+
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # Model singleton cache (module-level so they survive across node executions)
53
+ # ---------------------------------------------------------------------------
54
+ _occluder_sess: ort.InferenceSession | None = None
55
+ _xseg_sess: ort.InferenceSession | None = None
56
+ _face_detector: FaceAnalysis | None = None
57
+
58
+
59
+ def _get_occluder_session() -> ort.InferenceSession:
60
+ global _occluder_sess
61
+ if _occluder_sess is None:
62
+ path = os.path.join(os.path.dirname(__file__), "models", "occluder.onnx")
63
+ if not os.path.exists(path):
64
+ raise FileNotFoundError(f"occluder.onnx not found at: {path}")
65
+ _occluder_sess = ort.InferenceSession(path, providers=_ort_providers())
66
+ _logger.info("Loaded occluder.onnx")
67
+ return _occluder_sess
68
+
69
+
70
+ def _get_xseg_session() -> ort.InferenceSession:
71
+ global _xseg_sess
72
+ if _xseg_sess is None:
73
+ path = os.path.join(os.path.dirname(__file__), "models", "XSeg_model.onnx")
74
+ if not os.path.exists(path):
75
+ raise FileNotFoundError(f"XSeg_model.onnx not found at: {path}")
76
+ _xseg_sess = ort.InferenceSession(path, providers=_ort_providers())
77
+ _logger.info("Loaded XSeg_model.onnx")
78
+ return _xseg_sess
79
+
80
+
81
+ def _get_face_detector() -> FaceAnalysis:
82
+ global _face_detector
83
+ if _face_detector is None:
84
+ # Configure INSIGHTFACE_HOME β€” scan common locations
85
+ if not os.environ.get("INSIGHTFACE_HOME"):
86
+ candidates = [
87
+ os.path.join(os.path.dirname(__file__), "models", "insightface"),
88
+ os.path.join(os.path.dirname(__file__), "..", "..", "models", "insightface"),
89
+ os.path.join(os.path.expanduser("~"), ".insightface"),
90
+ ]
91
+ for p in candidates:
92
+ if os.path.exists(p):
93
+ os.environ["INSIGHTFACE_HOME"] = p
94
+ _logger.info(f"Set INSIGHTFACE_HOME β†’ {p}")
95
+ break
96
+ else:
97
+ _logger.warning(
98
+ "INSIGHTFACE_HOME not found in common paths. "
99
+ "Set INSIGHTFACE_HOME environment variable if face detection fails."
100
+ )
101
+
102
+ _face_detector = FaceAnalysis(providers=_ort_providers())
103
+ _face_detector.prepare(ctx_id=0 if torch.cuda.is_available() else -1)
104
+ _logger.info("Loaded InsightFace detector")
105
+ return _face_detector
106
+
107
+
108
+ # ---------------------------------------------------------------------------
109
+ # Low-level mask inference helpers
110
+ # ---------------------------------------------------------------------------
111
+
112
+
113
+ def _run_occluder(sess, img_chw):
114
+ """
115
+ Supports BOTH:
116
+ - NCHW : [1,3,256,256]
117
+ - NHWC : [1,256,256,3]
118
+ """
119
+
120
+ import numpy as np
121
+
122
+ inp_meta = sess.get_inputs()[0]
123
+ inp_name = inp_meta.name
124
+ inp_shape = inp_meta.shape
125
+
126
+ img = img_chw.astype(np.float32)
127
+
128
+ # normalize
129
+ if img.max() > 1.0:
130
+ img = img / 255.0
131
+
132
+ # NHWC model
133
+ if len(inp_shape) == 4 and inp_shape[-1] == 3:
134
+
135
+ # CHW -> HWC
136
+ img = np.transpose(img, (1, 2, 0))
137
+
138
+ # add batch
139
+ inp = np.expand_dims(img, 0)
140
+
141
+ else:
142
+ # NCHW
143
+ inp = np.expand_dims(img, 0)
144
+
145
+ out = sess.run(None, {inp_name: inp})[0]
146
+
147
+ out = np.squeeze(out)
148
+
149
+ return out
150
+
151
+
152
+
153
+
154
+ def _run_xseg(session, img_chw):
155
+ """
156
+ Run XSeg segmentation model.
157
+
158
+ Args:
159
+ session: onnxruntime.InferenceSession
160
+ img_chw: float32 CHW image in range [0,1]
161
+
162
+ Returns:
163
+ float32 mask HxW in range [0,1]
164
+ """
165
+
166
+ import cv2
167
+ import numpy as np
168
+
169
+ # CHW -> HWC
170
+ img = np.transpose(img_chw, (1, 2, 0))
171
+
172
+ # resize to model size
173
+ resized = cv2.resize(img, (256, 256))
174
+
175
+ # normalize
176
+ inp = resized.astype(np.float32)
177
+
178
+ # HWC -> NCHW
179
+ inp = np.transpose(inp, (2, 0, 1))[None]
180
+
181
+ input_name = session.get_inputs()[0].name
182
+
183
+ pred = session.run(None, {input_name: inp})[0]
184
+
185
+ # squeeze
186
+ pred = np.squeeze(pred)
187
+
188
+ # normalize mask
189
+ pred = np.clip(pred, 0.0, 1.0)
190
+
191
+ return pred.astype(np.float32)
192
+
193
+
194
+ def _compute_face_occluder_mask(
195
+ face_crop_rgb: np.ndarray, # uint8 [H, W, 3]
196
+ detection_sensitivity: float, # 0.0–1.0, higher = more objects detected
197
+ mask_mode: str, # "Hard" | "Soft"
198
+ mask_expansion: int, # pixels to expand mask outward (can be negative)
199
+ edge_softness: int, # gaussian blur radius after expansion
200
+ occluder_sess: ort.InferenceSession,
201
+ xseg_sess: ort.InferenceSession,
202
+ ) -> np.ndarray:
203
+ """
204
+ Returns a float32 [256, 256] mask in range [0,1].
205
+ 1 = occluded pixel (object in front of face) β†’ faceswap should NOT touch this.
206
+ 0 = clear face pixel β†’ faceswap can swap here.
207
+ """
208
+ # Resize to 256Γ—256 and normalize to [0, 1]
209
+ resized = cv2.resize(face_crop_rgb, (256, 256), interpolation=cv2.INTER_LINEAR)
210
+ img_f = resized.astype(np.float32) / 255.0 # [256, 256, 3]
211
+ img_chw = img_f.transpose(2, 0, 1) # [3, 256, 256]
212
+
213
+ # --- Model inference ---
214
+ occluder_mask = _run_occluder(occluder_sess, img_chw) # 1 = something covering face
215
+ face_skin_mask = _run_xseg(xseg_sess, img_chw) # 1 = face skin
216
+
217
+ # --- Combine: we want pixels that are OCCLUDED and NOT face skin ---
218
+ # Threshold for sensitivity: lower threshold = more objects detected
219
+ # detection_sensitivity 1.0 β†’ threshold 0.1 (very sensitive, catches more objects)
220
+ # detection_sensitivity 0.0 β†’ threshold 0.9 (strict, only very clear occlusions)
221
+ threshold = 1.0 - (detection_sensitivity * 0.8 + 0.1)
222
+
223
+ # Soft-threshold occluder mask
224
+ combined = np.clip(occluder_mask - face_skin_mask * 0.5, 0.0, 1.0)
225
+
226
+ if mask_mode == "Hard":
227
+ combined = (combined >= threshold).astype(np.float32)
228
+ else:
229
+ # Soft mode: keep the gradient but suppress below threshold
230
+ combined = np.where(combined < threshold * 0.5, 0.0, combined)
231
+ combined = np.clip(combined, 0.0, 1.0)
232
+
233
+ # --- Mask expansion (morphological dilation/erosion) ---
234
+ if mask_expansion != 0:
235
+ abs_exp = abs(mask_expansion)
236
+ # Use ellipse kernel for natural-looking edges
237
+ kernel = cv2.getStructuringElement(
238
+ cv2.MORPH_ELLIPSE, (2 * abs_exp + 1, 2 * abs_exp + 1)
239
+ )
240
+ if mask_expansion > 0:
241
+ combined = cv2.dilate(combined, kernel, iterations=1)
242
+ else:
243
+ combined = cv2.erode(combined, kernel, iterations=1)
244
+ combined = np.clip(combined, 0.0, 1.0)
245
+
246
+ # --- Edge softness (always applied AFTER expansion) ---
247
+ if edge_softness > 0:
248
+ ksize = edge_softness * 2 + 1
249
+ combined = cv2.GaussianBlur(combined, (ksize, ksize), 0)
250
+
251
+ return combined # float32 [256, 256]
252
+
253
+
254
+ # ---------------------------------------------------------------------------
255
+ # Debug preview image builder
256
+ # ---------------------------------------------------------------------------
257
+
258
+ def _build_preview(
259
+ orig_rgb: np.ndarray, # uint8 [H, W, 3]
260
+ full_mask: np.ndarray, # float32 [H, W] in [0, 1]
261
+ face_bboxes: list, # list of (x1,y1,x2,y2) in original image coords
262
+ ) -> np.ndarray:
263
+ """
264
+ Returns uint8 [H, W, 3] image:
265
+ - Red semi-transparent overlay on masked (protected) region
266
+ - Green bounding boxes around detected faces
267
+ """
268
+ preview = orig_rgb.copy().astype(np.float32)
269
+ H, W = orig_rgb.shape[:2]
270
+
271
+ # Red overlay for occluded/protected region
272
+ red_layer = np.zeros_like(preview)
273
+ red_layer[..., 0] = 255.0 # R channel
274
+
275
+ alpha = full_mask[..., None] * 0.6 # 60% opacity on masked area
276
+ preview = preview * (1.0 - alpha) + red_layer * alpha
277
+ preview = np.clip(preview, 0, 255).astype(np.uint8)
278
+
279
+ # Green face bounding boxes
280
+ for (x1, y1, x2, y2) in face_bboxes:
281
+ cv2.rectangle(preview, (x1, y1), (x2, y2), color=(0, 220, 60), thickness=2)
282
+
283
+ return preview
284
+
285
+
286
+ # ---------------------------------------------------------------------------
287
+ # Tensor ↔ numpy helpers
288
+ # ---------------------------------------------------------------------------
289
+
290
+ def _tensor_to_numpy_rgb(tensor: torch.Tensor) -> np.ndarray:
291
+ """
292
+ Accepts ComfyUI IMAGE tensor of shape [1, H, W, 3] or [H, W, 3].
293
+ Returns uint8 numpy array [H, W, 3].
294
+ """
295
+ arr = tensor.cpu().numpy()
296
+ arr = np.squeeze(arr)
297
+ if arr.ndim == 2:
298
+ arr = np.stack([arr, arr, arr], axis=-1)
299
+ if arr.ndim == 3 and arr.shape[0] in (1, 3) and arr.shape[-1] not in (1, 3):
300
+ arr = arr.transpose(1, 2, 0)
301
+ if arr.dtype != np.uint8:
302
+ arr = (np.clip(arr, 0.0, 1.0) * 255).astype(np.uint8)
303
+ if arr.shape[-1] == 1:
304
+ arr = np.repeat(arr, 3, axis=-1)
305
+ return arr # uint8 [H, W, 3]
306
+
307
+
308
+ def _numpy_rgb_to_tensor(arr: np.ndarray) -> torch.Tensor:
309
+ """uint8 [H, W, 3] β†’ float32 tensor [1, H, W, 3]"""
310
+ f = arr.astype(np.float32) / 255.0
311
+ return torch.from_numpy(f).unsqueeze(0) # [1, H, W, 3]
312
+
313
+
314
+ def _mask_numpy_to_tensor(mask: np.ndarray) -> torch.Tensor:
315
+ """float32 [H, W] β†’ float32 tensor [1, H, W]"""
316
+ return torch.from_numpy(mask[None, ...].copy()).float()
317
+
318
+
319
+ # ---------------------------------------------------------------------------
320
+ # Main node class
321
+ # ---------------------------------------------------------------------------
322
+
323
+ class OcclusionMask:
324
+ """
325
+ ComfyUI node: generates an occlusion protection mask for ReActor faceswap.
326
+
327
+ The MASK output marks pixels that are covered by objects in front of the face
328
+ (microphones, hands, glasses, food, etc.). Feed this mask into ReActor's
329
+ 'face_mask' input β€” ReActor will skip those pixels and preserve the occlusion.
330
+
331
+ Supports batch IMAGE inputs (list of [1,H,W,3] tensors or a single [N,H,W,3]).
332
+ """
333
+
334
+ # Singleton model cache β€” loaded once, reused across all executions
335
+ _occluder_sess: ort.InferenceSession | None = None
336
+ _xseg_sess: ort.InferenceSession | None = None
337
+ _face_detector: FaceAnalysis | None = None
338
+
339
+ @classmethod
340
+ def INPUT_TYPES(cls):
341
+ return {
342
+ "required": {
343
+ # ── Input ──────────────────────────────────────────────────
344
+ "input_image": (
345
+ "IMAGE",
346
+ {"forceInput": True, "label": "Input Image (pass-through to ReActor)"},
347
+ ),
348
+
349
+ # ── Detection ──────────────────────────────────────────────
350
+ "face_target": (
351
+ ["Largest face only", "All faces"],
352
+ {
353
+ "default": "Largest face only",
354
+ "label": "Face Target",
355
+ "tooltip": (
356
+ "Largest face only: fastest, best for single-subject images. "
357
+ "All faces: processes every detected face independently and unions the masks."
358
+ ),
359
+ },
360
+ ),
361
+ "face_crop_padding": (
362
+ "FLOAT",
363
+ {
364
+ "default": 0.15,
365
+ "min": 0.0,
366
+ "max": 0.5,
367
+ "step": 0.01,
368
+ "display": "slider",
369
+ "label": "Face Crop Padding (0–50%)",
370
+ "tooltip": (
371
+ "How much extra area around the detected face bounding box to include "
372
+ "before running the occlusion models. Increase if objects near the face "
373
+ "edges are being missed. 15% is a good default."
374
+ ),
375
+ },
376
+ ),
377
+ "fallback_to_full_image": (
378
+ "BOOLEAN",
379
+ {
380
+ "default": False,
381
+ "label": "Fallback to Full Image if No Face Found",
382
+ "tooltip": (
383
+ "If enabled and no face is detected, the entire image is treated as "
384
+ "the face region. Useful for heavily occluded faces. "
385
+ "Disable for safety to avoid accidental full-image masking."
386
+ ),
387
+ },
388
+ ),
389
+
390
+ # ── Sensitivity ────────────────────────────────────────────
391
+ "detection_sensitivity": (
392
+ "FLOAT",
393
+ {
394
+ "default": 0.65,
395
+ "min": 0.0,
396
+ "max": 1.0,
397
+ "step": 0.01,
398
+ "display": "slider",
399
+ "label": "Detection Sensitivity (0 = strict β†’ 1 = detect everything)",
400
+ "tooltip": (
401
+ "Controls how aggressively objects are detected.\n"
402
+ "LOW (0.2–0.4): only very prominent occlusions like a hand covering the face.\n"
403
+ "MID (0.5–0.7): good default β€” catches microphones, glasses, held objects.\n"
404
+ "HIGH (0.8–1.0): catches subtle occlusions but may bleed into face edges."
405
+ ),
406
+ },
407
+ ),
408
+
409
+ # ── Mask shape ─────────────────────────────────────────────
410
+ "mask_expansion": (
411
+ "INT",
412
+ {
413
+ "default": 6,
414
+ "min": -20,
415
+ "max": 50,
416
+ "step": 1,
417
+ "display": "slider",
418
+ "label": "Mask Expansion (-20 shrink ↔ +50 grow, px)",
419
+ "tooltip": (
420
+ "Expands (positive) or shrinks (negative) the detected occlusion mask.\n"
421
+ "Positive values add a safety margin around objects β€” recommended to avoid "
422
+ "faceswap pixels bleeding under object edges.\n"
423
+ "Negative values trim the mask if it's accidentally covering face skin."
424
+ ),
425
+ },
426
+ ),
427
+ "edge_softness": (
428
+ "INT",
429
+ {
430
+ "default": 4,
431
+ "min": 0,
432
+ "max": 30,
433
+ "step": 1,
434
+ "display": "slider",
435
+ "label": "Edge Softness (0 = hard edge β†’ 30 = very soft blend)",
436
+ "tooltip": (
437
+ "Gaussian blur applied to the mask AFTER expansion. "
438
+ "Soft edges create a smoother transition between the swapped face "
439
+ "and the preserved object, avoiding hard seams. "
440
+ "4–8px is recommended for most cases."
441
+ ),
442
+ },
443
+ ),
444
+ "mask_mode": (
445
+ ["Soft (recommended)", "Hard (binary)"],
446
+ {
447
+ "default": "Soft (recommended)",
448
+ "label": "Mask Mode",
449
+ "tooltip": (
450
+ "Soft: the mask retains gradient values (0.0–1.0) allowing partial "
451
+ "blending at object boundaries β€” best for natural-looking results.\n"
452
+ "Hard: mask is strictly 0 or 1 β€” use if ReActor produces ghosting "
453
+ "artifacts with soft masks."
454
+ ),
455
+ },
456
+ ),
457
+ }
458
+ }
459
+
460
+ RETURN_TYPES = ("IMAGE", "MASK", "IMAGE")
461
+ RETURN_NAMES = ("IMAGE", "MASK", "PREVIEW")
462
+ FUNCTION = "generate_occlusion_mask"
463
+ CATEGORY = "image/faceswap"
464
+
465
+ # ------------------------------------------------------------------
466
+ # Model accessors (lazy-load singletons)
467
+ # ------------------------------------------------------------------
468
+
469
+ @classmethod
470
+ def _get_occluder(cls) -> ort.InferenceSession:
471
+ if cls._occluder_sess is None:
472
+ cls._occluder_sess = _get_occluder_session()
473
+ return cls._occluder_sess
474
+
475
+ @classmethod
476
+ def _get_xseg(cls) -> ort.InferenceSession:
477
+ if cls._xseg_sess is None:
478
+ cls._xseg_sess = _get_xseg_session()
479
+ return cls._xseg_sess
480
+
481
+ @classmethod
482
+ def _get_detector(cls) -> FaceAnalysis:
483
+ if cls._face_detector is None:
484
+ cls._face_detector = _get_face_detector()
485
+ return cls._face_detector
486
+
487
+ # ------------------------------------------------------------------
488
+ # Face detection helpers
489
+ # ------------------------------------------------------------------
490
+
491
+ def _detect_faces(self, img_rgb: np.ndarray) -> list[tuple[int, int, int, int]]:
492
+ """Returns list of (x1, y1, x2, y2) bounding boxes, sorted largest-first."""
493
+ try:
494
+ faces = self._get_detector().get(img_rgb)
495
+ except Exception as e:
496
+ _logger.error(f"InsightFace detection failed: {e}")
497
+ return []
498
+ bboxes = []
499
+ for face in faces:
500
+ x1, y1, x2, y2 = face.bbox.astype(int)
501
+ # Clamp to image bounds
502
+ x1 = max(0, x1)
503
+ y1 = max(0, y1)
504
+ x2 = min(img_rgb.shape[1], x2)
505
+ y2 = min(img_rgb.shape[0], y2)
506
+ if x2 > x1 and y2 > y1:
507
+ bboxes.append((x1, y1, x2, y2))
508
+ # Sort largest area first
509
+ bboxes.sort(key=lambda b: (b[2]-b[0]) * (b[3]-b[1]), reverse=True)
510
+ return bboxes
511
+
512
+ def _pad_bbox(
513
+ self,
514
+ bbox: tuple[int, int, int, int],
515
+ img_w: int,
516
+ img_h: int,
517
+ padding: float,
518
+ ) -> tuple[int, int, int, int]:
519
+ """Expand bbox by `padding` fraction, clamped to image dimensions."""
520
+ x1, y1, x2, y2 = bbox
521
+ pw = int((x2 - x1) * padding)
522
+ ph = int((y2 - y1) * padding)
523
+ return (
524
+ max(0, x1 - pw),
525
+ max(0, y1 - ph),
526
+ min(img_w, x2 + pw),
527
+ min(img_h, y2 + ph),
528
+ )
529
+
530
+ # ------------------------------------------------------------------
531
+ # Single-image processing
532
+ # ------------------------------------------------------------------
533
+
534
+ def _process_single_image(
535
+ self,
536
+ img_rgb: np.ndarray, # uint8 [H, W, 3]
537
+ face_target: str,
538
+ face_crop_padding: float,
539
+ fallback_to_full_image: bool,
540
+ detection_sensitivity: float,
541
+ mask_expansion: int,
542
+ edge_softness: int,
543
+ mask_mode: str,
544
+ ) -> tuple[np.ndarray, np.ndarray]:
545
+ """
546
+ Returns:
547
+ full_mask: float32 [H, W] β€” the protection mask (1 = occluded, preserve)
548
+ preview: uint8 [H, W, 3] β€” debug overlay image
549
+ """
550
+ H, W = img_rgb.shape[:2]
551
+ full_mask = np.zeros((H, W), dtype=np.float32)
552
+
553
+ # 1. Detect faces
554
+ bboxes = self._detect_faces(img_rgb)
555
+
556
+ if not bboxes:
557
+ _logger.warning("No faces detected in image.")
558
+ if fallback_to_full_image:
559
+ _logger.info("Fallback: treating full image as face region.")
560
+ bboxes = [(0, 0, W, H)]
561
+ else:
562
+ # Return empty mask + annotated preview
563
+ preview = _build_preview(img_rgb, full_mask, [])
564
+ return full_mask, preview
565
+
566
+ # 2. Select which faces to process
567
+ if face_target == "Largest face only":
568
+ bboxes_to_process = [bboxes[0]]
569
+ else:
570
+ bboxes_to_process = bboxes
571
+
572
+ # 3. Per-face mask computation
573
+ for bbox in bboxes_to_process:
574
+ padded = self._pad_bbox(bbox, W, H, face_crop_padding)
575
+ px1, py1, px2, py2 = padded
576
+ crop_h, crop_w = py2 - py1, px2 - px1
577
+
578
+ # Crop the face region
579
+ face_crop = img_rgb[py1:py2, px1:px2]
580
+
581
+ # Run occlusion inference at 256Γ—256
582
+ mask_256 = _compute_face_occluder_mask(
583
+ face_crop_rgb=face_crop,
584
+ detection_sensitivity=detection_sensitivity,
585
+ mask_mode="Hard" if mask_mode.startswith("Hard") else "Soft",
586
+ mask_expansion=mask_expansion,
587
+ edge_softness=edge_softness,
588
+ occluder_sess=self._get_occluder(),
589
+ xseg_sess=self._get_xseg(),
590
+ ) # float32 [256, 256]
591
+
592
+ # Resize mask back to crop region size
593
+ mask_crop = cv2.resize(
594
+ mask_256, (crop_w, crop_h), interpolation=cv2.INTER_LINEAR
595
+ )
596
+
597
+ # Union into full-image mask
598
+ full_mask[py1:py2, px1:px2] = np.maximum(
599
+ full_mask[py1:py2, px1:px2], mask_crop
600
+ )
601
+
602
+ full_mask = np.clip(full_mask, 0.0, 1.0)
603
+
604
+ # 4. Build debug preview
605
+ preview = _build_preview(img_rgb, full_mask, bboxes_to_process)
606
+
607
+ return full_mask, preview
608
+
609
+ # ------------------------------------------------------------------
610
+ # Main entry point
611
+ # ------------------------------------------------------------------
612
+
613
+ def generate_occlusion_mask(
614
+ self,
615
+ input_image: torch.Tensor,
616
+ face_target: str = "Largest face only",
617
+ face_crop_padding: float = 0.15,
618
+ fallback_to_full_image: bool = False,
619
+ detection_sensitivity: float = 0.65,
620
+ mask_expansion: int = 6,
621
+ edge_softness: int = 4,
622
+ mask_mode: str = "Soft (recommended)",
623
+ ):
624
+ """
625
+ Accepts ComfyUI IMAGE tensors in two formats:
626
+ - Single: [1, H, W, 3] float32
627
+ - Batch: [N, H, W, 3] float32
628
+ - List: list of [1, H, W, 3] tensors (from BatchLoadImages OUTPUT_IS_LIST)
629
+
630
+ Returns: (IMAGE, MASK, PREVIEW) β€” each matching the batch dimension of the input.
631
+ """
632
+ occluder_sess = self._get_occluder() # warm up before batch loop
633
+ xseg_sess = self._get_xseg()
634
+ _ = occluder_sess, xseg_sess # keep references alive
635
+
636
+ # ── Normalise input to a list of individual uint8 [H,W,3] arrays ──
637
+ if isinstance(input_image, list):
638
+ # List of tensors from BatchLoadImages (OUTPUT_IS_LIST=True)
639
+ frames_np = [_tensor_to_numpy_rgb(t) for t in input_image]
640
+ was_list = True
641
+ elif isinstance(input_image, torch.Tensor):
642
+ t = input_image
643
+ if t.ndim == 3:
644
+ t = t.unsqueeze(0) # [H,W,3] β†’ [1,H,W,3]
645
+ # t is now [N, H, W, 3]
646
+ frames_np = [_tensor_to_numpy_rgb(t[i].unsqueeze(0)) for i in range(t.shape[0])]
647
+ was_list = False
648
+ else:
649
+ raise TypeError(f"Unsupported input_image type: {type(input_image)}")
650
+
651
+ out_images = []
652
+ out_masks = []
653
+ out_previews = []
654
+
655
+ for img_rgb in frames_np:
656
+ full_mask, preview = self._process_single_image(
657
+ img_rgb=img_rgb,
658
+ face_target=face_target,
659
+ face_crop_padding=face_crop_padding,
660
+ fallback_to_full_image=fallback_to_full_image,
661
+ detection_sensitivity=detection_sensitivity,
662
+ mask_expansion=mask_expansion,
663
+ edge_softness=edge_softness,
664
+ mask_mode=mask_mode,
665
+ )
666
+ out_images.append(_numpy_rgb_to_tensor(img_rgb)) # [1,H,W,3] passthrough
667
+ out_masks.append(_mask_numpy_to_tensor(full_mask)) # [1,H,W]
668
+ out_previews.append(_numpy_rgb_to_tensor(preview)) # [1,H,W,3]
669
+
670
+ # ── Pack outputs back into the right format ──
671
+ if len(out_images) == 1 and not was_list:
672
+ # Single image β€” return [1,H,W,3] tensors directly
673
+ image_out = out_images[0]
674
+ mask_out = out_masks[0]
675
+ preview_out = out_previews[0]
676
+ else:
677
+ # Batch β€” concatenate along dim 0
678
+ # For MASK, ComfyUI expects [N, H, W] so we cat the [1,H,W] tensors
679
+ image_out = torch.cat(out_images, dim=0) # [N,H,W,3]
680
+ mask_out = torch.cat(out_masks, dim=0) # [N,H,W]
681
+ preview_out = torch.cat(out_previews, dim=0) # [N,H,W,3]
682
+
683
+ return (image_out, mask_out, preview_out)
684
+
685
+