Nekochu commited on
Commit
7b2ad18
·
1 Parent(s): 33e616b

blue screen support: GPU-only, auto-detection, no ONNX/LFS

Browse files

- Auto-detect screen color from first frame background pixels
- Blue model downloaded from nikopueringer/CorridorKeyBlue_1.0 on first use
- fast_chromascreen_mask: green (HSV 35-85) + blue (HSV 100-130)
- despill supports screen_channel=1 (green) or 2 (blue) in both numpy and torch
- Model cache keyed by (img_size, screen_color)
- CPU/ONNX path: green model only, despill adapts to detected color
- UI: Auto/Green/Blue radio. CLI: --screen-color flag

Files changed (1) hide show
  1. app.py +123 -67
app.py CHANGED
@@ -68,9 +68,11 @@ CORRIDORKEY_MODELS = {
68
  "1024": os.path.join(MODELS_DIR, "corridorkey_1024.onnx"),
69
  "2048": os.path.join(MODELS_DIR, "corridorkey_2048.onnx"),
70
  }
71
- CORRIDORKEY_REPO = "nikopueringer/CorridorKey_v1.0"
72
- CORRIDORKEY_SAFETENSORS = "CorridorKey_v1.0.safetensors"
73
- CORRIDORKEY_PTH_FALLBACK = "CorridorKey_v1.0.pth"
 
 
74
  IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32).reshape(1, 1, 3)
75
  IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32).reshape(1, 1, 3)
76
  MAX_DURATION_CPU = 5
@@ -83,21 +85,23 @@ HAS_CUDA = "CUDAExecutionProvider" in ort.get_available_providers()
83
  # ---------------------------------------------------------------------------
84
  logger.info("Preloading model files at startup...")
85
  _preloaded_birefnet_path = None
86
- _preloaded_ckpt_path = None
87
  try:
88
  _preloaded_birefnet_path = hf_hub_download(repo_id=BIREFNET_REPO, filename=BIREFNET_FILE)
89
  logger.info("BiRefNet cached: %s", _preloaded_birefnet_path)
90
  except Exception as e:
91
  logger.warning("BiRefNet preload failed (will retry later): %s", e)
 
92
  try:
93
- _preloaded_ckpt_path = hf_hub_download(repo_id=CORRIDORKEY_REPO, filename=CORRIDORKEY_SAFETENSORS)
94
- logger.info("CorridorKey.safetensors cached: %s", _preloaded_ckpt_path)
 
95
  except Exception:
96
  try:
97
- _preloaded_ckpt_path = hf_hub_download(repo_id=CORRIDORKEY_REPO, filename=CORRIDORKEY_PTH_FALLBACK)
98
- logger.info("CorridorKey.pth fallback cached: %s", _preloaded_ckpt_path)
99
  except Exception as e:
100
- logger.warning("CorridorKey preload failed (will retry later): %s", e)
101
 
102
  # Batch sizes for GPU inference (conservative for H200 80GB)
103
  GPU_BATCH_SIZES = {"1024": 32, "2048": 16} # 2048 uses only 5.7GB/batch=2, so 16 easily fits in 69.8GB
@@ -116,14 +120,18 @@ def srgb_to_linear(x):
116
  def composite_straight(fg, bg, alpha):
117
  return fg * alpha + bg * (1.0 - alpha)
118
 
119
- def despill(image, green_limit_mode="average", strength=1.0):
120
  if strength <= 0.0:
121
  return image
122
- r, g, b = image[..., 0], image[..., 1], image[..., 2]
123
- limit = (r + b) / 2.0 if green_limit_mode == "average" else np.maximum(r, b)
124
- spill = np.maximum(g - limit, 0.0)
125
- despilled = np.stack([r + spill * 0.5, g - spill, b + spill * 0.5], axis=-1)
126
- return image * (1.0 - strength) + despilled * strength if strength < 1.0 else despilled
 
 
 
 
127
 
128
  def clean_matte(alpha_np, area_threshold=300, dilation=15, blur_size=5):
129
  is_3d = alpha_np.ndim == 3
@@ -214,9 +222,30 @@ def clean_matte_torch(alpha, area_threshold, dilation=25, blur_size=5):
214
 
215
 
216
  # ---------------------------------------------------------------------------
217
- # Fast classical green-screen mask
218
  # ---------------------------------------------------------------------------
219
- def fast_greenscreen_mask(frame_rgb_f32):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  h, w = frame_rgb_f32.shape[:2]
221
  ph, pw = max(int(h * 0.05), 4), max(int(w * 0.05), 4)
222
  corners = np.concatenate([
@@ -226,17 +255,27 @@ def fast_greenscreen_mask(frame_rgb_f32):
226
  frame_rgb_f32[-ph:, -pw:].reshape(-1, 3),
227
  ], axis=0)
228
  bg_color = np.median(corners, axis=0)
229
- if not (bg_color[1] > bg_color[0] + 0.05 and bg_color[1] > bg_color[2] + 0.05):
230
- return None, 0.0
 
 
 
 
 
 
 
231
  frame_u8 = (np.clip(frame_rgb_f32, 0, 1) * 255).astype(np.uint8)
232
  hsv = cv2.cvtColor(frame_u8, cv2.COLOR_RGB2HSV)
233
- green_mask = cv2.inRange(hsv, (35, 40, 40), (85, 255, 255))
234
- fg_mask = cv2.bitwise_not(green_mask)
 
 
 
235
  fg_mask = cv2.morphologyEx(fg_mask, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)))
236
  fg_mask = cv2.GaussianBlur(fg_mask, (5, 5), 0)
237
  mask_f32 = fg_mask.astype(np.float32) / 255.0
238
  confidence = 1.0 - 2.0 * np.mean(np.minimum(mask_f32, 1.0 - mask_f32))
239
- return mask_f32, confidence
240
 
241
  # ---------------------------------------------------------------------------
242
  # ONNX model loading (CPU fallback + BiRefNet)
@@ -303,21 +342,22 @@ def get_corridorkey_onnx(resolution="1024"):
303
  # PyTorch model loading (GPU path)
304
  # ---------------------------------------------------------------------------
305
  _pytorch_model = None
306
- _pytorch_model_size = None
307
 
308
- def _load_greenformer(img_size):
309
  """Load the GreenFormer PyTorch model for GPU inference."""
310
  import torch
311
  import torch.nn.functional as F
312
  from CorridorKeyModule.core.model_transformer import GreenFormer
313
 
314
- if _preloaded_ckpt_path:
315
- checkpoint_path = _preloaded_ckpt_path
316
  else:
 
317
  try:
318
- checkpoint_path = hf_hub_download(repo_id=CORRIDORKEY_REPO, filename=CORRIDORKEY_SAFETENSORS)
319
  except Exception:
320
- checkpoint_path = hf_hub_download(repo_id=CORRIDORKEY_REPO, filename=CORRIDORKEY_PTH_FALLBACK)
321
  logger.info("Using checkpoint: %s", checkpoint_path)
322
 
323
  logger.info("Initializing GreenFormer (img_size=%d)...", img_size)
@@ -398,19 +438,19 @@ def _load_greenformer(img_size):
398
  return model
399
 
400
 
401
- def get_pytorch_model(img_size):
402
- """Get or load the PyTorch GreenFormer model for the given resolution."""
403
- global _pytorch_model, _pytorch_model_size
404
- if _pytorch_model is None or _pytorch_model_size != img_size:
405
- # Free old model if switching resolution
406
  if _pytorch_model is not None:
407
  import torch
408
  del _pytorch_model
409
  _pytorch_model = None
410
  torch.cuda.empty_cache()
411
  gc.collect()
412
- _pytorch_model = _load_greenformer(img_size)
413
- _pytorch_model_size = img_size
414
  return _pytorch_model
415
 
416
 
@@ -427,7 +467,8 @@ def birefnet_frame(session, image_rgb_uint8):
427
  return (cv2.resize(pred[0, 0], (w, h)) > 0.04).astype(np.float32)
428
 
429
  def corridorkey_frame_onnx(session, image_f32, mask_f32, img_size,
430
- despill_strength=0.5, auto_despeckle=True, despeckle_size=400):
 
431
  """ONNX inference for a single frame (CPU path)."""
432
  h, w = image_f32.shape[:2]
433
  img_r = cv2.resize(image_f32, (img_size, img_size))
@@ -441,7 +482,7 @@ def corridorkey_frame_onnx(session, image_f32, mask_f32, img_size,
441
  alpha = alpha[:, :, np.newaxis]
442
  if auto_despeckle:
443
  alpha = clean_matte(alpha, area_threshold=despeckle_size, dilation=25, blur_size=5)
444
- fg = despill(fg, green_limit_mode="average", strength=despill_strength)
445
  return {"alpha": alpha, "fg": fg}
446
 
447
 
@@ -449,7 +490,8 @@ def corridorkey_frame_onnx(session, image_f32, mask_f32, img_size,
449
  # Batched inference: PyTorch (GPU path)
450
  # ---------------------------------------------------------------------------
451
  def corridorkey_batch_pytorch(model, images_f32, masks_f32, img_size,
452
- despill_strength=0.5, auto_despeckle=True, despeckle_size=400):
 
453
  """PyTorch batched inference with full GPU pipeline (preprocess + inference + postprocess on device)."""
454
  import torch
455
  import torchvision.transforms.functional as TF
@@ -489,7 +531,7 @@ def corridorkey_batch_pytorch(model, images_f32, masks_f32, img_size,
489
 
490
  if auto_despeckle:
491
  alpha = clean_matte_torch(alpha, area_threshold=int(despeckle_size), dilation=25, blur_size=5)
492
- fg = despill_torch(fg, despill_strength)
493
 
494
  # --- Single CPU transfer at the end ---
495
  alpha_np = alpha.cpu().numpy()
@@ -564,7 +606,7 @@ def _gpu_decorator(fn):
564
  @_gpu_decorator
565
  def _gpu_phase(video_path, resolution, despill_val, mask_mode,
566
  auto_despeckle, despeckle_size, progress=gr.Progress(),
567
- precompute_dir=None, precompute_count=0):
568
  """ALL GPU work: load models, read video, generate masks, run inference, write frames."""
569
  if video_path is None:
570
  raise gr.Error("Please upload a video.")
@@ -583,6 +625,7 @@ def _gpu_phase(video_path, resolution, despill_val, mask_mode,
583
  img_size = int(resolution)
584
  max_dur = MAX_DURATION_GPU if use_gpu else MAX_DURATION_CPU
585
  despill_strength = despill_val / 10.0
 
586
 
587
  # Read video metadata
588
  cap = cv2.VideoCapture(video_path)
@@ -618,7 +661,7 @@ def _gpu_phase(video_path, resolution, despill_val, mask_mode,
618
  batch_size = GPU_BATCH_SIZES.get(resolution, 16) if use_gpu else 1
619
  if use_gpu:
620
  progress(0.05, desc=f"Loading GreenFormer ({resolution})...")
621
- pytorch_model = get_pytorch_model(img_size)
622
  else:
623
  progress(0.05, desc=f"Loading CorridorKey ONNX ({resolution})...")
624
  corridorkey_onnx = get_corridorkey_onnx(resolution)
@@ -677,10 +720,10 @@ def _gpu_phase(video_path, resolution, despill_val, mask_mode,
677
  frame_f32 = frame_rgb.astype(np.float32) / 255.0
678
  tm = time.time()
679
  if mask_mode == "Fast (classical)":
680
- mask, _ = fast_greenscreen_mask(frame_f32)
681
  fast_n += 1
682
  elif mask_mode == "Hybrid (auto)":
683
- mask, conf = fast_greenscreen_mask(frame_f32)
684
  if mask is None or conf < 0.7:
685
  mask = birefnet_frame(birefnet, frame_rgb)
686
  biref_n += 1
@@ -706,6 +749,7 @@ def _gpu_phase(video_path, resolution, despill_val, mask_mode,
706
  despill_strength=despill_strength,
707
  auto_despeckle=auto_despeckle,
708
  despeckle_size=int(despeckle_size),
 
709
  )
710
  t_inf = time.time() - t_inf
711
 
@@ -754,10 +798,11 @@ def _gpu_phase(video_path, resolution, despill_val, mask_mode,
754
  "results": "written", "frame_times": frame_times,
755
  "use_gpu": True, "batch_size": batch_size,
756
  "w": w, "h": h, "fps": fps, "tmpdir": tmpdir,
 
757
  }
758
 
759
  else:
760
- # CPU PATH: sequential ONNX + inline writes (no GPU budget concern)
761
  bg_lin = srgb_to_linear(create_checkerboard(w, h))
762
  comp_dir, fg_dir = os.path.join(tmpdir, "Comp"), os.path.join(tmpdir, "FG")
763
  matte_dir, processed_dir = os.path.join(tmpdir, "Matte"), os.path.join(tmpdir, "Processed")
@@ -773,11 +818,11 @@ def _gpu_phase(video_path, resolution, despill_val, mask_mode,
773
  frame_f32 = frame_rgb.astype(np.float32) / 255.0
774
 
775
  if mask_mode == "Fast (classical)":
776
- mask, _ = fast_greenscreen_mask(frame_f32)
777
  if mask is None:
778
  raise gr.Error("Fast mask failed. Try 'AI (BiRefNet)' mode.")
779
  elif mask_mode == "Hybrid (auto)":
780
- mask, conf = fast_greenscreen_mask(frame_f32)
781
  if mask is None or conf < 0.7:
782
  mask = birefnet_frame(birefnet, frame_rgb)
783
  else:
@@ -786,7 +831,8 @@ def _gpu_phase(video_path, resolution, despill_val, mask_mode,
786
  result = corridorkey_frame_onnx(corridorkey_onnx, frame_f32, mask, img_size,
787
  despill_strength=despill_strength,
788
  auto_despeckle=auto_despeckle,
789
- despeckle_size=int(despeckle_size))
 
790
  _write_frame(i, result["alpha"], result["fg"],
791
  w, h, bg_lin, comp_dir, fg_dir, matte_dir, processed_dir)
792
 
@@ -811,33 +857,35 @@ def _gpu_phase(video_path, resolution, despill_val, mask_mode,
811
 
812
 
813
  def process_video(video_path, resolution, despill_val, mask_mode,
814
- auto_despeckle, despeckle_size, progress=gr.Progress()):
 
815
  """Orchestrator: precompute fast masks (CPU) → GPU inference → CPU I/O."""
816
  t_total = time.time()
817
  if video_path is None:
818
  raise gr.Error("Please upload a video.")
819
 
820
- # Phase 0: Precompute fast masks on CPU and save to disk.
821
- # IMPORTANT: Can't pass large data as args to @spaces.GPU (ZeroGPU serializes args).
822
- # Save to a numpy file, pass only the path.
823
  logger.info("[Phase 0] Precomputing fast masks on CPU")
824
  t_mask = time.time()
825
  precompute_dir = tempfile.mkdtemp(prefix="ck_pre_")
826
  cap = cv2.VideoCapture(video_path)
827
  frame_count = 0
828
  needs_birefnet = False
 
829
  while True:
830
  ret, frame_bgr = cap.read()
831
  if not ret:
832
  break
833
  frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
834
  frame_f32 = frame_rgb.astype(np.float32) / 255.0
 
 
 
835
  if mask_mode == "Fast (classical)":
836
- mask, _ = fast_greenscreen_mask(frame_f32)
837
  if mask is None:
838
  raise gr.Error("Fast mask failed. Try 'Hybrid' or 'AI' mode.")
839
  elif mask_mode == "Hybrid (auto)":
840
- mask, conf = fast_greenscreen_mask(frame_f32)
841
  if mask is None or conf < 0.7:
842
  mask = None
843
  needs_birefnet = True
@@ -849,15 +897,15 @@ def process_video(video_path, resolution, despill_val, mask_mode,
849
  np.save(os.path.join(precompute_dir, f"mask_{frame_count:05d}.npy"), mask)
850
  frame_count += 1
851
  cap.release()
852
- logger.info("[Phase 0] %d frames saved to %s in %.1fs (needs_birefnet=%s)",
853
- frame_count, precompute_dir, time.time() - t_mask, needs_birefnet)
854
 
855
- # Phase 1: GPU inference — pass only paths (tiny strings), not data
856
  logger.info("[Phase 1] Starting GPU phase")
857
  t0 = time.time()
858
  data = _gpu_phase(video_path, resolution, despill_val, mask_mode,
859
  auto_despeckle, despeckle_size, progress,
860
- precompute_dir=precompute_dir, precompute_count=frame_count)
 
861
  logger.info("[process_video] GPU phase done in %.1fs", time.time() - t0)
862
 
863
  tmpdir = data["tmpdir"]
@@ -901,7 +949,8 @@ def process_video(video_path, resolution, despill_val, mask_mode,
901
  status = (f"Processed {n} frames ({w}x{h}) at {resolution}px | "
902
  f"{avg:.2f}s/frame | {engine}" +
903
  (f" batch={batch_size}" if use_gpu else "") +
904
- f" | {wall:.0f}s total")
 
905
 
906
  return (
907
  comp_video if os.path.exists(comp_video) else None,
@@ -926,12 +975,12 @@ def process_video(video_path, resolution, despill_val, mask_mode,
926
  # ---------------------------------------------------------------------------
927
  # Gradio UI
928
  # ---------------------------------------------------------------------------
929
- def process_example(video_path, resolution, despill, mask_mode, despeckle, despeckle_size):
930
- return process_video(video_path, resolution, despill, mask_mode, despeckle, despeckle_size)
931
 
932
- DESCRIPTION = """# CorridorKey Green Screen Matting
933
- Remove green backgrounds from video. Based on [CorridorKey](https://www.youtube.com/watch?v=3Ploi723hg4) by Corridor Digital.
934
- ZeroGPU H200: batched PyTorch inference (up to 32 frames at once). CPU fallback via ONNX."""
935
 
936
  with gr.Blocks(title="CorridorKey") as demo:
937
  gr.Markdown(DESCRIPTION)
@@ -962,6 +1011,11 @@ with gr.Blocks(title="CorridorKey") as demo:
962
  value=400, precision=0, label="Despeckle Size",
963
  info="Min pixel area to keep"
964
  )
 
 
 
 
 
965
  process_btn = gr.Button("Process Video", variant="primary", size="lg")
966
 
967
  with gr.Column(scale=1):
@@ -973,9 +1027,9 @@ with gr.Blocks(title="CorridorKey") as demo:
973
 
974
  gr.Examples(
975
  examples=[
976
- ["examples/corridor_greenscreen_demo.mp4", "1024", 5, "Hybrid (auto)", True, 400],
977
  ],
978
- inputs=[input_video, resolution, despill_slider, mask_mode, despeckle_check, despeckle_size],
979
  outputs=[comp_video, matte_video, download_zip, status_text],
980
  fn=process_example,
981
  cache_examples=True,
@@ -985,7 +1039,7 @@ with gr.Blocks(title="CorridorKey") as demo:
985
 
986
  process_btn.click(
987
  fn=process_video,
988
- inputs=[input_video, resolution, despill_slider, mask_mode, despeckle_check, despeckle_size],
989
  outputs=[comp_video, matte_video, download_zip, status_text],
990
  )
991
 
@@ -1005,6 +1059,7 @@ def cli_main():
1005
  parser.add_argument("--despill", type=int, default=5)
1006
  parser.add_argument("--no-despeckle", action="store_true")
1007
  parser.add_argument("--despeckle-size", type=int, default=400)
 
1008
  args = parser.parse_args()
1009
 
1010
  global HAS_CUDA
@@ -1018,7 +1073,8 @@ def cli_main():
1018
 
1019
  comp, matte, zipf, status = process_video(
1020
  args.input, args.resolution, args.despill, args.mask_mode,
1021
- not args.no_despeckle, args.despeckle_size, progress=CLIProgress()
 
1022
  )
1023
  print(f"\n{status}")
1024
  os.makedirs(args.output, exist_ok=True)
 
68
  "1024": os.path.join(MODELS_DIR, "corridorkey_1024.onnx"),
69
  "2048": os.path.join(MODELS_DIR, "corridorkey_2048.onnx"),
70
  }
71
+ CORRIDORKEY_CHECKPOINTS = {
72
+ "green": {"repo": "nikopueringer/CorridorKey_v1.0", "safetensors": "CorridorKey_v1.0.safetensors", "pth": "CorridorKey_v1.0.pth"},
73
+ "blue": {"repo": "nikopueringer/CorridorKeyBlue_1.0", "safetensors": "CorridorKeyBlue_1.0.safetensors", "pth": "CorridorKeyBlue_1.0.pth"},
74
+ }
75
+ SCREEN_CHANNEL = {"green": 1, "blue": 2}
76
  IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32).reshape(1, 1, 3)
77
  IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32).reshape(1, 1, 3)
78
  MAX_DURATION_CPU = 5
 
85
  # ---------------------------------------------------------------------------
86
  logger.info("Preloading model files at startup...")
87
  _preloaded_birefnet_path = None
88
+ _preloaded_ckpt = {}
89
  try:
90
  _preloaded_birefnet_path = hf_hub_download(repo_id=BIREFNET_REPO, filename=BIREFNET_FILE)
91
  logger.info("BiRefNet cached: %s", _preloaded_birefnet_path)
92
  except Exception as e:
93
  logger.warning("BiRefNet preload failed (will retry later): %s", e)
94
+ # Preload green checkpoint only (blue is lazy-loaded on first use)
95
  try:
96
+ c = CORRIDORKEY_CHECKPOINTS["green"]
97
+ _preloaded_ckpt["green"] = hf_hub_download(repo_id=c["repo"], filename=c["safetensors"])
98
+ logger.info("CorridorKey green cached: %s", _preloaded_ckpt["green"])
99
  except Exception:
100
  try:
101
+ _preloaded_ckpt["green"] = hf_hub_download(repo_id=c["repo"], filename=c["pth"])
102
+ logger.info("CorridorKey green .pth cached: %s", _preloaded_ckpt["green"])
103
  except Exception as e:
104
+ logger.warning("CorridorKey green preload failed: %s", e)
105
 
106
  # Batch sizes for GPU inference (conservative for H200 80GB)
107
  GPU_BATCH_SIZES = {"1024": 32, "2048": 16} # 2048 uses only 5.7GB/batch=2, so 16 easily fits in 69.8GB
 
120
  def composite_straight(fg, bg, alpha):
121
  return fg * alpha + bg * (1.0 - alpha)
122
 
123
+ def despill(image, strength=1.0, screen_channel=1):
124
  if strength <= 0.0:
125
  return image
126
+ other_a, other_b = [i for i in (0, 1, 2) if i != screen_channel]
127
+ screen = image[..., screen_channel]
128
+ a, b = image[..., other_a], image[..., other_b]
129
+ spill = np.maximum(screen - (a + b) / 2.0, 0.0)
130
+ out = np.empty_like(image)
131
+ out[..., screen_channel] = screen - spill
132
+ out[..., other_a] = a + spill * 0.5
133
+ out[..., other_b] = b + spill * 0.5
134
+ return image * (1.0 - strength) + out * strength if strength < 1.0 else out
135
 
136
  def clean_matte(alpha_np, area_threshold=300, dilation=15, blur_size=5):
137
  is_3d = alpha_np.ndim == 3
 
222
 
223
 
224
  # ---------------------------------------------------------------------------
225
+ # Screen color detection + fast classical mask
226
  # ---------------------------------------------------------------------------
227
+ def estimate_screen_color(frame_f32, alpha_hint=None):
228
+ """Detect green vs blue screen from background pixels. Returns 'green' or 'blue'."""
229
+ if alpha_hint is not None:
230
+ if alpha_hint.ndim == 3:
231
+ alpha_hint = alpha_hint[:, :, 0]
232
+ bg_mask = alpha_hint < 0.3
233
+ else:
234
+ h, w = frame_f32.shape[:2]
235
+ ph, pw = max(int(h * 0.05), 4), max(int(w * 0.05), 4)
236
+ bg_mask = np.zeros((h, w), dtype=bool)
237
+ bg_mask[:ph, :pw] = bg_mask[:ph, -pw:] = bg_mask[-ph:, :pw] = bg_mask[-ph:, -pw:] = True
238
+ if bg_mask.mean() < 0.01:
239
+ return "green"
240
+ bg = frame_f32[bg_mask]
241
+ mean_g, mean_b = float(bg[:, 1].mean()), float(bg[:, 2].mean())
242
+ if abs(mean_g - mean_b) < 0.05:
243
+ return "green"
244
+ return "blue" if mean_b > mean_g else "green"
245
+
246
+
247
+ def fast_chromascreen_mask(frame_rgb_f32, screen_color="auto"):
248
+ """Fast classical mask for green or blue screens. Returns (mask, confidence, detected_color)."""
249
  h, w = frame_rgb_f32.shape[:2]
250
  ph, pw = max(int(h * 0.05), 4), max(int(w * 0.05), 4)
251
  corners = np.concatenate([
 
255
  frame_rgb_f32[-ph:, -pw:].reshape(-1, 3),
256
  ], axis=0)
257
  bg_color = np.median(corners, axis=0)
258
+ is_green = bg_color[1] > bg_color[0] + 0.05 and bg_color[1] > bg_color[2] + 0.05
259
+ is_blue = bg_color[2] > bg_color[0] + 0.05 and bg_color[2] > bg_color[1] + 0.05
260
+ if screen_color == "green" and not is_green:
261
+ return None, 0.0, "green"
262
+ if screen_color == "blue" and not is_blue:
263
+ return None, 0.0, "blue"
264
+ if screen_color == "auto" and not is_green and not is_blue:
265
+ return None, 0.0, "green"
266
+ detected = screen_color if screen_color != "auto" else ("blue" if is_blue and not is_green else "green")
267
  frame_u8 = (np.clip(frame_rgb_f32, 0, 1) * 255).astype(np.uint8)
268
  hsv = cv2.cvtColor(frame_u8, cv2.COLOR_RGB2HSV)
269
+ if detected == "blue":
270
+ screen_mask = cv2.inRange(hsv, (100, 40, 40), (130, 255, 255))
271
+ else:
272
+ screen_mask = cv2.inRange(hsv, (35, 40, 40), (85, 255, 255))
273
+ fg_mask = cv2.bitwise_not(screen_mask)
274
  fg_mask = cv2.morphologyEx(fg_mask, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)))
275
  fg_mask = cv2.GaussianBlur(fg_mask, (5, 5), 0)
276
  mask_f32 = fg_mask.astype(np.float32) / 255.0
277
  confidence = 1.0 - 2.0 * np.mean(np.minimum(mask_f32, 1.0 - mask_f32))
278
+ return mask_f32, confidence, detected
279
 
280
  # ---------------------------------------------------------------------------
281
  # ONNX model loading (CPU fallback + BiRefNet)
 
342
  # PyTorch model loading (GPU path)
343
  # ---------------------------------------------------------------------------
344
  _pytorch_model = None
345
+ _pytorch_model_key = None
346
 
347
+ def _load_greenformer(img_size, screen_color="green"):
348
  """Load the GreenFormer PyTorch model for GPU inference."""
349
  import torch
350
  import torch.nn.functional as F
351
  from CorridorKeyModule.core.model_transformer import GreenFormer
352
 
353
+ if screen_color in _preloaded_ckpt:
354
+ checkpoint_path = _preloaded_ckpt[screen_color]
355
  else:
356
+ c = CORRIDORKEY_CHECKPOINTS[screen_color]
357
  try:
358
+ checkpoint_path = hf_hub_download(repo_id=c["repo"], filename=c["safetensors"])
359
  except Exception:
360
+ checkpoint_path = hf_hub_download(repo_id=c["repo"], filename=c["pth"])
361
  logger.info("Using checkpoint: %s", checkpoint_path)
362
 
363
  logger.info("Initializing GreenFormer (img_size=%d)...", img_size)
 
438
  return model
439
 
440
 
441
+ def get_pytorch_model(img_size, screen_color="green"):
442
+ """Get or load the PyTorch GreenFormer model for the given resolution and screen color."""
443
+ global _pytorch_model, _pytorch_model_key
444
+ key = (img_size, screen_color)
445
+ if _pytorch_model is None or _pytorch_model_key != key:
446
  if _pytorch_model is not None:
447
  import torch
448
  del _pytorch_model
449
  _pytorch_model = None
450
  torch.cuda.empty_cache()
451
  gc.collect()
452
+ _pytorch_model = _load_greenformer(img_size, screen_color)
453
+ _pytorch_model_key = key
454
  return _pytorch_model
455
 
456
 
 
467
  return (cv2.resize(pred[0, 0], (w, h)) > 0.04).astype(np.float32)
468
 
469
  def corridorkey_frame_onnx(session, image_f32, mask_f32, img_size,
470
+ despill_strength=0.5, auto_despeckle=True, despeckle_size=400,
471
+ screen_channel=1):
472
  """ONNX inference for a single frame (CPU path)."""
473
  h, w = image_f32.shape[:2]
474
  img_r = cv2.resize(image_f32, (img_size, img_size))
 
482
  alpha = alpha[:, :, np.newaxis]
483
  if auto_despeckle:
484
  alpha = clean_matte(alpha, area_threshold=despeckle_size, dilation=25, blur_size=5)
485
+ fg = despill(fg, strength=despill_strength, screen_channel=screen_channel)
486
  return {"alpha": alpha, "fg": fg}
487
 
488
 
 
490
  # Batched inference: PyTorch (GPU path)
491
  # ---------------------------------------------------------------------------
492
  def corridorkey_batch_pytorch(model, images_f32, masks_f32, img_size,
493
+ despill_strength=0.5, auto_despeckle=True, despeckle_size=400,
494
+ screen_channel=1):
495
  """PyTorch batched inference with full GPU pipeline (preprocess + inference + postprocess on device)."""
496
  import torch
497
  import torchvision.transforms.functional as TF
 
531
 
532
  if auto_despeckle:
533
  alpha = clean_matte_torch(alpha, area_threshold=int(despeckle_size), dilation=25, blur_size=5)
534
+ fg = despill_torch(fg, despill_strength, screen_channel=screen_channel)
535
 
536
  # --- Single CPU transfer at the end ---
537
  alpha_np = alpha.cpu().numpy()
 
606
  @_gpu_decorator
607
  def _gpu_phase(video_path, resolution, despill_val, mask_mode,
608
  auto_despeckle, despeckle_size, progress=gr.Progress(),
609
+ precompute_dir=None, precompute_count=0, screen_color="green"):
610
  """ALL GPU work: load models, read video, generate masks, run inference, write frames."""
611
  if video_path is None:
612
  raise gr.Error("Please upload a video.")
 
625
  img_size = int(resolution)
626
  max_dur = MAX_DURATION_GPU if use_gpu else MAX_DURATION_CPU
627
  despill_strength = despill_val / 10.0
628
+ screen_ch = SCREEN_CHANNEL.get(screen_color, 1)
629
 
630
  # Read video metadata
631
  cap = cv2.VideoCapture(video_path)
 
661
  batch_size = GPU_BATCH_SIZES.get(resolution, 16) if use_gpu else 1
662
  if use_gpu:
663
  progress(0.05, desc=f"Loading GreenFormer ({resolution})...")
664
+ pytorch_model = get_pytorch_model(img_size, screen_color)
665
  else:
666
  progress(0.05, desc=f"Loading CorridorKey ONNX ({resolution})...")
667
  corridorkey_onnx = get_corridorkey_onnx(resolution)
 
720
  frame_f32 = frame_rgb.astype(np.float32) / 255.0
721
  tm = time.time()
722
  if mask_mode == "Fast (classical)":
723
+ mask, _, _ = fast_chromascreen_mask(frame_f32, screen_color)
724
  fast_n += 1
725
  elif mask_mode == "Hybrid (auto)":
726
+ mask, conf, _ = fast_chromascreen_mask(frame_f32, screen_color)
727
  if mask is None or conf < 0.7:
728
  mask = birefnet_frame(birefnet, frame_rgb)
729
  biref_n += 1
 
749
  despill_strength=despill_strength,
750
  auto_despeckle=auto_despeckle,
751
  despeckle_size=int(despeckle_size),
752
+ screen_channel=screen_ch,
753
  )
754
  t_inf = time.time() - t_inf
755
 
 
798
  "results": "written", "frame_times": frame_times,
799
  "use_gpu": True, "batch_size": batch_size,
800
  "w": w, "h": h, "fps": fps, "tmpdir": tmpdir,
801
+ "screen_color": screen_color,
802
  }
803
 
804
  else:
805
+ # CPU PATH: ONNX green-only (no blue ONNX models). Despill still uses detected screen_ch.
806
  bg_lin = srgb_to_linear(create_checkerboard(w, h))
807
  comp_dir, fg_dir = os.path.join(tmpdir, "Comp"), os.path.join(tmpdir, "FG")
808
  matte_dir, processed_dir = os.path.join(tmpdir, "Matte"), os.path.join(tmpdir, "Processed")
 
818
  frame_f32 = frame_rgb.astype(np.float32) / 255.0
819
 
820
  if mask_mode == "Fast (classical)":
821
+ mask, _, _ = fast_chromascreen_mask(frame_f32, screen_color)
822
  if mask is None:
823
  raise gr.Error("Fast mask failed. Try 'AI (BiRefNet)' mode.")
824
  elif mask_mode == "Hybrid (auto)":
825
+ mask, conf, _ = fast_chromascreen_mask(frame_f32, screen_color)
826
  if mask is None or conf < 0.7:
827
  mask = birefnet_frame(birefnet, frame_rgb)
828
  else:
 
831
  result = corridorkey_frame_onnx(corridorkey_onnx, frame_f32, mask, img_size,
832
  despill_strength=despill_strength,
833
  auto_despeckle=auto_despeckle,
834
+ despeckle_size=int(despeckle_size),
835
+ screen_channel=screen_ch)
836
  _write_frame(i, result["alpha"], result["fg"],
837
  w, h, bg_lin, comp_dir, fg_dir, matte_dir, processed_dir)
838
 
 
857
 
858
 
859
  def process_video(video_path, resolution, despill_val, mask_mode,
860
+ auto_despeckle, despeckle_size, screen_color="Auto",
861
+ progress=gr.Progress()):
862
  """Orchestrator: precompute fast masks (CPU) → GPU inference → CPU I/O."""
863
  t_total = time.time()
864
  if video_path is None:
865
  raise gr.Error("Please upload a video.")
866
 
 
 
 
867
  logger.info("[Phase 0] Precomputing fast masks on CPU")
868
  t_mask = time.time()
869
  precompute_dir = tempfile.mkdtemp(prefix="ck_pre_")
870
  cap = cv2.VideoCapture(video_path)
871
  frame_count = 0
872
  needs_birefnet = False
873
+ detected_color = screen_color.lower() if screen_color != "Auto" else "auto"
874
  while True:
875
  ret, frame_bgr = cap.read()
876
  if not ret:
877
  break
878
  frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
879
  frame_f32 = frame_rgb.astype(np.float32) / 255.0
880
+ if frame_count == 0 and detected_color == "auto":
881
+ detected_color = estimate_screen_color(frame_f32)
882
+ logger.info("Auto-detected screen color: %s", detected_color)
883
  if mask_mode == "Fast (classical)":
884
+ mask, _, _ = fast_chromascreen_mask(frame_f32, detected_color)
885
  if mask is None:
886
  raise gr.Error("Fast mask failed. Try 'Hybrid' or 'AI' mode.")
887
  elif mask_mode == "Hybrid (auto)":
888
+ mask, conf, _ = fast_chromascreen_mask(frame_f32, detected_color)
889
  if mask is None or conf < 0.7:
890
  mask = None
891
  needs_birefnet = True
 
897
  np.save(os.path.join(precompute_dir, f"mask_{frame_count:05d}.npy"), mask)
898
  frame_count += 1
899
  cap.release()
900
+ logger.info("[Phase 0] %d frames (%s screen) in %.1fs (needs_birefnet=%s)",
901
+ frame_count, detected_color, time.time() - t_mask, needs_birefnet)
902
 
 
903
  logger.info("[Phase 1] Starting GPU phase")
904
  t0 = time.time()
905
  data = _gpu_phase(video_path, resolution, despill_val, mask_mode,
906
  auto_despeckle, despeckle_size, progress,
907
+ precompute_dir=precompute_dir, precompute_count=frame_count,
908
+ screen_color=detected_color)
909
  logger.info("[process_video] GPU phase done in %.1fs", time.time() - t0)
910
 
911
  tmpdir = data["tmpdir"]
 
949
  status = (f"Processed {n} frames ({w}x{h}) at {resolution}px | "
950
  f"{avg:.2f}s/frame | {engine}" +
951
  (f" batch={batch_size}" if use_gpu else "") +
952
+ f" | {wall:.0f}s total"
953
+ + (f" | {data.get('screen_color', 'green')} screen" if data.get('screen_color', 'green') != 'green' else ""))
954
 
955
  return (
956
  comp_video if os.path.exists(comp_video) else None,
 
975
  # ---------------------------------------------------------------------------
976
  # Gradio UI
977
  # ---------------------------------------------------------------------------
978
+ def process_example(video_path, resolution, despill, mask_mode, despeckle, despeckle_size, screen_color="Auto"):
979
+ return process_video(video_path, resolution, despill, mask_mode, despeckle, despeckle_size, screen_color)
980
 
981
+ DESCRIPTION = """# CorridorKey Green/Blue Screen Matting
982
+ Remove green or blue screen backgrounds from video. Based on [CorridorKey](https://www.youtube.com/watch?v=3Ploi723hg4) by Corridor Digital.
983
+ ZeroGPU H200: batched PyTorch inference (up to 32 frames at once). Blue screen requires GPU. CPU fallback via ONNX (green only)."""
984
 
985
  with gr.Blocks(title="CorridorKey") as demo:
986
  gr.Markdown(DESCRIPTION)
 
1011
  value=400, precision=0, label="Despeckle Size",
1012
  info="Min pixel area to keep"
1013
  )
1014
+ screen_color = gr.Radio(
1015
+ choices=["Auto", "Green", "Blue"],
1016
+ value="Auto", label="Screen Color",
1017
+ info="Auto-detects from first frame. Blue screen requires GPU"
1018
+ )
1019
  process_btn = gr.Button("Process Video", variant="primary", size="lg")
1020
 
1021
  with gr.Column(scale=1):
 
1027
 
1028
  gr.Examples(
1029
  examples=[
1030
+ ["examples/corridor_greenscreen_demo.mp4", "1024", 5, "Hybrid (auto)", True, 400, "Auto"],
1031
  ],
1032
+ inputs=[input_video, resolution, despill_slider, mask_mode, despeckle_check, despeckle_size, screen_color],
1033
  outputs=[comp_video, matte_video, download_zip, status_text],
1034
  fn=process_example,
1035
  cache_examples=True,
 
1039
 
1040
  process_btn.click(
1041
  fn=process_video,
1042
+ inputs=[input_video, resolution, despill_slider, mask_mode, despeckle_check, despeckle_size, screen_color],
1043
  outputs=[comp_video, matte_video, download_zip, status_text],
1044
  )
1045
 
 
1059
  parser.add_argument("--despill", type=int, default=5)
1060
  parser.add_argument("--no-despeckle", action="store_true")
1061
  parser.add_argument("--despeckle-size", type=int, default=400)
1062
+ parser.add_argument("--screen-color", default="Auto", choices=["Auto", "Green", "Blue"])
1063
  args = parser.parse_args()
1064
 
1065
  global HAS_CUDA
 
1073
 
1074
  comp, matte, zipf, status = process_video(
1075
  args.input, args.resolution, args.despill, args.mask_mode,
1076
+ not args.no_despeckle, args.despeckle_size, args.screen_color,
1077
+ progress=CLIProgress()
1078
  )
1079
  print(f"\n{status}")
1080
  os.makedirs(args.output, exist_ok=True)