from __future__ import annotations import argparse import json import sys from pathlib import Path from typing import Optional import cv2 import numpy as np ROOT = Path(__file__).resolve().parent APM = ROOT / "automation_pose_mask" if str(APM) not in sys.path: sys.path.insert(0, str(APM)) from automation_pose_mask.openpose import OpenposeDetector # noqa: E402 def openpose_to_equifashion_candidate(candidate: list, subset: list) -> list[list[float]]: """ Convert OpenPose (candidate/subset) to EquiFashion-style candidate list. Output: list of [x, y, conf, joint_index] for joint_index 0..17 (COCO-18 body). """ cand = np.asarray(candidate, dtype=np.float64) if cand.size == 0 or cand.ndim != 2: return [[0.0, 0.0, 0.0, float(j)] for j in range(18)] sub = np.asarray(subset, dtype=np.float64) if sub.size == 0: return [[0.0, 0.0, 0.0, float(j)] for j in range(18)] person = sub[0] out: list[list[float]] = [] for j in range(18): idx = int(person[j]) if idx < 0: out.append([0.0, 0.0, 0.0, float(j)]) else: x, y, conf = float(cand[idx, 0]), float(cand[idx, 1]), float(cand[idx, 2]) out.append([x, y, conf, float(j)]) return out def _load_train_captions(train_json: Path) -> dict[str, str]: """ Load EquiFashion_DB/train.json captions. Returns: mapping {gt_filename -> caption}. """ if not train_json.is_file(): return {} data = json.loads(train_json.read_text(encoding="utf-8")) if not isinstance(data, list): return {} out: dict[str, str] = {} for r in data: if not isinstance(r, dict): continue gt = str(r.get("gt", "")).strip() if not gt: continue out[Path(gt).name] = str(r.get("caption", "")).strip() return out def run_equifashion_train_pose( *, equi_root: Path, body_model: Path, hand_model: Path, write_summary_json: bool, overwrite_existing: bool, out_size: int, limit: int, only_gt: Optional[str], fix_bright: bool, bright_threshold: float, ) -> None: """ Extract pose canvas (black background) + keypoints JSON for EquiFashion_DB/train. """ train_dir = equi_root / "train" train_json = equi_root / "train.json" out_pose_dir = equi_root / "train_pose" / "pose" out_json_dir = equi_root / "train_pose" / "json" if not train_dir.is_dir(): raise SystemExit(f"Không tìm thấy thư mục train: {train_dir}") if not body_model.is_file() or not hand_model.is_file(): raise SystemExit( f"Cần file model OpenPose tại:\n {body_model}\n {hand_model}\n" "(tải body_pose_model.pth / hand_pose_model.pth từ pytorch-openpose / ControlNet bundle)." ) cap_map = _load_train_captions(train_json) out_pose_dir.mkdir(parents=True, exist_ok=True) out_json_dir.mkdir(parents=True, exist_ok=True) op = OpenposeDetector(body_model_path=str(body_model), hand_model_path=str(hand_model)) exts = {".jpg", ".jpeg", ".png", ".webp"} img_paths = [p for p in sorted(train_dir.iterdir()) if p.is_file() and p.suffix.lower() in exts] if only_gt: want = Path(only_gt).name img_paths = [p for p in img_paths if p.name == want] if limit > 0: img_paths = img_paths[:limit] if not img_paths: raise SystemExit(f"Không có ảnh trong {train_dir}") processed = 0 skipped = 0 failed = 0 fixed = 0 print(f"Found {len(img_paths)} image(s) to process. overwrite_existing={overwrite_existing}, size={out_size}", flush=True) for p in img_paths: gt = p.name stem = p.stem pose_path = out_pose_dir / gt json_path = out_json_dir / f"{stem}.json" # Optional repair: if an existing pose looks like the original image (too bright), # regenerate it (and JSON) even when overwrite is off. if fix_bright and pose_path.is_file(): try: existing = cv2.imread(str(pose_path), cv2.IMREAD_COLOR) if existing is not None and float(existing.mean()) > float(bright_threshold): # treat as wrong pose (likely original image), regenerate below fixed += 1 else: # looks fine; if json exists too, we can skip safely if (not overwrite_existing) and json_path.is_file(): skipped += 1 continue except Exception: pass # Skip only when both outputs exist and overwrite is off. if (not overwrite_existing) and pose_path.is_file() and json_path.is_file(): skipped += 1 continue bgr = cv2.imread(str(p), cv2.IMREAD_COLOR) if bgr is None: failed += 1 continue # Resize input before OpenPose so keypoints match the saved canvas size. if out_size > 0 and (bgr.shape[0] != out_size or bgr.shape[1] != out_size): bgr = cv2.resize(bgr, (out_size, out_size), interpolation=cv2.INTER_AREA) # Black canvas output; keep models loaded for batch speed. canvas, keypoints = op(bgr, draw_on_image=False, auto_offload=False) # OpenPose returns RGB; OpenCV writes BGR. ok_pose = cv2.imwrite(str(pose_path), canvas[:, :, ::-1]) if not ok_pose: failed += 1 continue equif = openpose_to_equifashion_candidate(keypoints.get("candidate") or [], keypoints.get("subset") or []) json_path.write_text(json.dumps({"candidate": equif}, ensure_ascii=False), encoding="utf-8") processed += 1 if processed % 200 == 0: print(f"progress: processed={processed}, fixed={fixed}, skipped={skipped}, failed={failed}", flush=True) if write_summary_json: summary: list[dict[str, str]] = [] for p in img_paths: gt = p.name if not (out_pose_dir / gt).is_file(): continue summary.append( { "gt": gt, "caption": cap_map.get(gt, ""), "pose": f"train_pose/pose/{gt}".replace("\\", "/"), } ) (equi_root / "train_pose.json").write_text( json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8", ) print( "EquiFashion train pose done: " f"processed={processed}, fixed={fixed}, skipped={skipped}, failed={failed}, out={equi_root / 'train_pose'}" ) # Free memory at the end. try: op.offload() except Exception: pass def main() -> None: ap = argparse.ArgumentParser(description="Batch OpenPose canvas for EquiFashion_DB/train -> train_pose") ap.add_argument( "--body-model", type=Path, default=ROOT / "model" / "body_pose_model.pth", help="OpenPose body weights", ) ap.add_argument( "--hand-model", type=Path, default=ROOT / "model" / "hand_pose_model.pth", help="OpenPose hand weights", ) ap.add_argument( "--equifashion-root", type=Path, default=ROOT / "EquiFashion_DB", help="EquiFashion_DB root (contains train/, train.json, ...).", ) ap.add_argument( "--write-train-pose-json", action="store_true", help="Write EquiFashion_DB/train_pose.json (list of {gt, caption, pose}).", ) ap.add_argument( "--overwrite-existing", action="store_true", help="Overwrite existing pose/json (default: skip).", ) ap.add_argument( "--pose-size", type=int, default=512, help="Force input and output to size×size (default: 512).", ) ap.add_argument( "--limit", type=int, default=0, help="Process only the first N images (0 = all).", ) ap.add_argument( "--only-gt", type=str, default=None, help="Process only one file by gt name (e.g. 000611.jpg).", ) ap.add_argument( "--fix-bright", action="store_true", help="Repair existing pose files that look too bright (likely the original image).", ) ap.add_argument( "--bright-threshold", type=float, default=30.0, help="Mean-pixel threshold to treat a pose as 'bright' (default: 30).", ) args = ap.parse_args() if not args.body_model.is_file() or not args.hand_model.is_file(): raise SystemExit( f"Cần file model OpenPose tại:\n {args.body_model}\n {args.hand_model}\n" "(tải body_pose_model.pth / hand_pose_model.pth từ pytorch-openpose / ControlNet bundle)." ) run_equifashion_train_pose( equi_root=Path(args.equifashion_root).resolve(), body_model=Path(args.body_model).resolve(), hand_model=Path(args.hand_model).resolve(), write_summary_json=bool(args.write_train_pose_json), overwrite_existing=bool(args.overwrite_existing), out_size=int(args.pose_size), limit=int(args.limit), only_gt=str(args.only_gt) if args.only_gt else None, fix_bright=bool(args.fix_bright), bright_threshold=float(args.bright_threshold), ) if __name__ == "__main__": main()