Download reconstruction/scripts/run_interformer.py from hk239/v2d: direct link, hf CLI and curl.
- Browser
- Download file 10.7 kB
-
https://huggingface.co/datasets/hk239/v2d/resolve/main/reconstruction/scripts/run_interformer.py
- Command line
-
hf download hf://datasets/hk239/v2d/reconstruction/scripts/run_interformer.py
-
curl -L -o run_interformer.py https://huggingface.co/datasets/hk239/v2d/resolve/main/reconstruction/scripts/run_interformer.py
10.7 kB
| #!/usr/bin/env python3 | |
| """Run InterFormer (egocentric hand–object parsing) on every frame of a clip. | |
| Does not import third-party/do-as-i-do. Uses reconstruction/modules/InterFormer. | |
| Output (default: <video_dir>/video_segmentation/interformer/): | |
| masks/frame_XXXXXX_masks/<class>.png | |
| overlays/frame_XXXXXX.png | |
| semantic/frame_XXXXXX.png | |
| tracked_interformer.mp4 | |
| 6-class EgoHOS names (config_interformer.py num_classes=6): | |
| background, left_hand, right_hand, left_object, right_object, two_object | |
| Union object mask is also written as <object_id>.png (default: object). | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import os | |
| import subprocess | |
| import sys | |
| from pathlib import Path | |
| import cv2 | |
| import numpy as np | |
| _RECON_ROOT = Path(__file__).resolve().parents[1] | |
| _IF_DIR = Path(os.environ.get("INTERFORMER_DIR", _RECON_ROOT / "modules" / "InterFormer")) | |
| sys.path.insert(0, str(_IF_DIR)) | |
| def _raise_mmdet_mmcv_cap() -> None: | |
| """mmdet 3.x asserts mmcv<2.2.0; source-built mmcv for torch 2.11 is 2.2.0.""" | |
| try: | |
| import site | |
| paths = [] | |
| try: | |
| paths.extend(site.getsitepackages()) | |
| except Exception: | |
| pass | |
| try: | |
| paths.append(site.getusersitepackages()) | |
| except Exception: | |
| pass | |
| for sp in paths: | |
| init = Path(sp) / "mmdet" / "__init__.py" | |
| if not init.is_file(): | |
| continue | |
| text = init.read_text() | |
| if "mmcv_maximum_version = '2.2.0'" in text: | |
| init.write_text( | |
| text.replace( | |
| "mmcv_maximum_version = '2.2.0'", | |
| "mmcv_maximum_version = '2.3.0'", | |
| ) | |
| ) | |
| except OSError: | |
| pass | |
| _raise_mmdet_mmcv_cap() | |
| EGOHOS6 = [ | |
| "background", | |
| "left_hand", | |
| "right_hand", | |
| "left_object", | |
| "right_object", | |
| "two_object", | |
| ] | |
| EGOHOS9 = [ | |
| "background", | |
| "left_hand", | |
| "right_hand", | |
| "left_object", | |
| "right_object", | |
| "two_object", | |
| "left_object2", | |
| "right_object2", | |
| "two_object2", | |
| ] | |
| PALETTE = np.array( | |
| [ | |
| [0, 0, 0], | |
| [255, 0, 0], | |
| [0, 0, 255], | |
| [255, 0, 255], | |
| [0, 255, 255], | |
| [0, 255, 0], | |
| [255, 204, 255], | |
| [204, 255, 255], | |
| [204, 255, 204], | |
| ], | |
| dtype=np.uint8, | |
| ) | |
| OBJECT_CLASSES = { | |
| "left_object", | |
| "right_object", | |
| "two_object", | |
| "left_object2", | |
| "right_object2", | |
| "two_object2", | |
| } | |
| def _find_checkpoint(explicit: str | None) -> Path: | |
| if explicit: | |
| p = Path(explicit) | |
| if not p.is_file(): | |
| raise FileNotFoundError(f"checkpoint not found: {p}") | |
| return p | |
| env = os.environ.get("INTERFORMER_CHECKPOINT") | |
| if env: | |
| p = Path(env) | |
| if p.is_file(): | |
| return p | |
| ckpt_dir = Path( | |
| os.environ.get( | |
| "INTERFORMER_CKPT_DIR", | |
| _RECON_ROOT.parent / "checkpoints" / "interformer", | |
| ) | |
| ) | |
| if ckpt_dir.is_file(): | |
| return ckpt_dir | |
| hits: list[Path] = [] | |
| if ckpt_dir.is_dir(): | |
| for pat in ("*.pth", "*.pt", "*.ckpt"): | |
| hits.extend(sorted(ckpt_dir.glob(pat))) | |
| hits.extend(sorted(ckpt_dir.glob(f"**/{pat}"))) | |
| hits = [h for h in hits if h.is_file() and "backbone" not in h.name.lower()] | |
| if hits: | |
| return hits[0] | |
| raise FileNotFoundError( | |
| "No InterFormer weights under checkpoints/interformer.\n" | |
| "Put the trained .pth there (README: Google Drive " | |
| "https://drive.google.com/file/d/172Hi0jTTijEnbroYSUZgOfpsyue_HHxg )." | |
| ) | |
| def _list_frames(video: str, frames_dir: str | None) -> list[Path]: | |
| if frames_dir: | |
| d = Path(frames_dir) | |
| frames = sorted(d.glob("*.png")) + sorted(d.glob("*.jpg")) | |
| if not frames: | |
| raise FileNotFoundError(f"no images in {d}") | |
| return frames | |
| vp = Path(video) | |
| if vp.is_dir(): | |
| frames = sorted(vp.glob("*.png")) + sorted(vp.glob("*.jpg")) | |
| if frames: | |
| return frames | |
| raise FileNotFoundError(f"no images in {vp}") | |
| sibling = vp.parent / "all_frames" | |
| if sibling.is_dir(): | |
| frames = sorted(sibling.glob("*.png")) | |
| if frames: | |
| return frames | |
| cap = cv2.VideoCapture(str(vp)) | |
| if not cap.isOpened(): | |
| raise FileNotFoundError(f"cannot open {vp}") | |
| tmp = vp.parent / "all_frames" | |
| tmp.mkdir(parents=True, exist_ok=True) | |
| i = 0 | |
| while True: | |
| ok, bgr = cap.read() | |
| if not ok: | |
| break | |
| out = tmp / f"{i:06d}.png" | |
| if not out.exists(): | |
| cv2.imwrite(str(out), bgr) | |
| i += 1 | |
| cap.release() | |
| return sorted(tmp.glob("*.png")) | |
| def _colorize(sem: np.ndarray) -> np.ndarray: | |
| h, w = sem.shape | |
| rgb = np.zeros((h, w, 3), dtype=np.uint8) | |
| for i in range(min(len(PALETTE), int(sem.max()) + 1)): | |
| rgb[sem == i] = PALETTE[i] | |
| return rgb | |
| def main() -> int: | |
| p = argparse.ArgumentParser(description="InterFormer HOI segmentation on all frames") | |
| p.add_argument("--video", type=str, default=None, help="clip.mp4 or a frames directory") | |
| p.add_argument("--frames-dir", type=str, default=None, help="directory of PNG/JPG frames") | |
| p.add_argument("--output-dir", type=str, default=None) | |
| p.add_argument("--checkpoint", type=str, default=None) | |
| p.add_argument( | |
| "--config", | |
| type=str, | |
| default=None, | |
| help="default: modules/InterFormer/mmseg/configs/config_interformer.py", | |
| ) | |
| p.add_argument("--object-id", type=str, default="object", help="filename for union object mask") | |
| p.add_argument("--device", type=str, default=None) | |
| p.add_argument("--skip-existing", action="store_true") | |
| args = p.parse_args() | |
| if not args.video and not args.frames_dir: | |
| p.error("pass --video or --frames-dir") | |
| ckpt = _find_checkpoint(args.checkpoint) | |
| cfg_path = Path( | |
| args.config | |
| or os.environ.get( | |
| "INTERFORMER_CONFIG", | |
| _IF_DIR / "mmseg" / "configs" / "config_interformer.py", | |
| ) | |
| ) | |
| if not cfg_path.is_file(): | |
| raise FileNotFoundError(f"InterFormer config missing: {cfg_path}") | |
| frames = _list_frames(args.video or "", args.frames_dir) | |
| if args.output_dir: | |
| out_root = Path(args.output_dir) | |
| else: | |
| base = Path(args.video).resolve().parent if args.video else frames[0].parent.parent | |
| if (base / "clip.mp4").exists() or (base / "all_frames").exists(): | |
| out_root = base / "video_segmentation" / "interformer" | |
| else: | |
| out_root = base / "interformer" | |
| masks_root = out_root / "masks" | |
| overlay_dir = out_root / "overlays" | |
| semantic_dir = out_root / "semantic" | |
| overlay_dir.mkdir(parents=True, exist_ok=True) | |
| semantic_dir.mkdir(parents=True, exist_ok=True) | |
| device = args.device or ("cuda:0" if os.environ.get("CUDA_VISIBLE_DEVICES") is not None else "cuda:0") | |
| try: | |
| import torch | |
| if not torch.cuda.is_available(): | |
| device = "cpu" | |
| except ImportError: | |
| pass | |
| print(f"InterFormer config: {cfg_path}") | |
| print(f"checkpoint: {ckpt}") | |
| print(f"frames: {len(frames)} out: {out_root}") | |
| from mmseg.apis import inference_model, init_model | |
| model = init_model(str(cfg_path), str(ckpt), device=device) | |
| ncls = int(model.decode_head.num_classes) | |
| names = EGOHOS6 if ncls <= 6 else EGOHOS9 | |
| names = names[:ncls] | |
| print(f"classes ({ncls}): {names}") | |
| nonempty = {n: 0 for n in names} | |
| for i, fpath in enumerate(frames): | |
| frame_i = i | |
| stem_digits = "".join(ch for ch in fpath.stem if ch.isdigit()) | |
| if stem_digits: | |
| frame_i = int(stem_digits) | |
| frame_dir = masks_root / f"frame_{frame_i:06d}_masks" | |
| obj_png = frame_dir / f"{args.object_id}.png" | |
| if args.skip_existing and obj_png.is_file(): | |
| m = cv2.imread(str(obj_png), cv2.IMREAD_GRAYSCALE) | |
| if m is not None and int(m.max()) > 0: | |
| print(f"[{i+1}/{len(frames)}] skip {fpath.name}") | |
| continue | |
| bgr = cv2.imread(str(fpath), cv2.IMREAD_COLOR) | |
| if bgr is None: | |
| print(f"skip unreadable {fpath}", file=sys.stderr) | |
| continue | |
| h0, w0 = bgr.shape[:2] | |
| result = inference_model(model, str(fpath)) | |
| sem = result.pred_sem_seg.data.cpu().numpy() | |
| if sem.ndim == 3: | |
| sem = sem[0] | |
| if sem.shape[0] != h0 or sem.shape[1] != w0: | |
| sem = cv2.resize(sem.astype(np.uint8), (w0, h0), interpolation=cv2.INTER_NEAREST) | |
| frame_dir.mkdir(parents=True, exist_ok=True) | |
| union_obj = np.zeros((h0, w0), dtype=np.uint8) | |
| for cid, cname in enumerate(names): | |
| if cname == "background": | |
| continue | |
| binm = (sem == cid).astype(np.uint8) * 255 | |
| if binm.max() > 0: | |
| nonempty[cname] += 1 | |
| cv2.imwrite(str(frame_dir / f"{cname}.png"), binm) | |
| if cname in OBJECT_CLASSES: | |
| union_obj = np.maximum(union_obj, binm) | |
| if cname == "right_hand": | |
| cv2.imwrite(str(frame_dir / "right_hand_0.png"), binm) | |
| if cname == "left_hand": | |
| cv2.imwrite(str(frame_dir / "left_hand_0.png"), binm) | |
| cv2.imwrite(str(obj_png), union_obj) | |
| color = _colorize(sem) | |
| overlay = cv2.addWeighted(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB), 0.55, color, 0.45, 0) | |
| cv2.imwrite( | |
| str(overlay_dir / f"frame_{frame_i:06d}.png"), | |
| cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR), | |
| ) | |
| cv2.imwrite(str(semantic_dir / f"frame_{frame_i:06d}.png"), cv2.cvtColor(color, cv2.COLOR_RGB2BGR)) | |
| cov = 100.0 * (union_obj > 0).mean() | |
| print(f"[{i+1}/{len(frames)}] {fpath.name} object_cov={cov:.2f}%") | |
| ffmpeg = os.environ.get("FFMPEG") or shutil_which("ffmpeg") | |
| if ffmpeg and overlay_dir.glob("frame_*.png"): | |
| mp4 = out_root / "tracked_interformer.mp4" | |
| subprocess.run( | |
| [ | |
| ffmpeg, "-y", "-framerate", "24", | |
| "-i", str(overlay_dir / "frame_%06d.png"), | |
| "-c:v", "libx264", "-pix_fmt", "yuv420p", str(mp4), | |
| ], | |
| check=False, | |
| ) | |
| print(f"video: {mp4}") | |
| print("nonempty frames per class:") | |
| for n, c in nonempty.items(): | |
| if n == "background": | |
| continue | |
| print(f" {n}: {c}/{len(frames)}") | |
| print(f"done: {out_root}") | |
| return 0 | |
| def shutil_which(name: str) -> str | None: | |
| import shutil | |
| return shutil.which(name) | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |