Datasets:
File size: 9,752 Bytes
9dc0e5b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 | 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()
|