107 lines
6.7 KiB
Python
107 lines
6.7 KiB
Python
"""无头跑 HUG:对采集目录里的 RGB-D,在指定像素(或 camera.json 里记录的物体像素)处采样 N 个人手抓取。
|
||
|
||
解释器:$HUG_PYTHON(HUG 环境)。
|
||
用法(仓库根目录):HF_HUB_OFFLINE=1 "$HUG_PYTHON" scripts/hug_infer_point.py \
|
||
--capture data/capture_ready --object jar --num 16 [--steps 1]
|
||
输出:<capture>/hug_<object>.npz —— landmarks_cam (N,21,3) / landmarks_world (N,21,3) / T_cam_wrist (N,4,4) /
|
||
T_world_wrist (N,4,4) / pose_aa (N,15,3) / verts_world (N,778,3) / click_world (3,)
|
||
landmark 顺序(HUG=MANO/OpenPose-21):0 腕,1-4 拇指(根→尖),5-8 食指,9-12 中指,13-16 无名指,17-20 小指。
|
||
"""
|
||
import argparse, json, pickle, sys, time
|
||
from pathlib import Path
|
||
from project_paths import configured_path
|
||
import numpy as np, torch, cv2
|
||
|
||
|
||
def main():
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--capture", required=True); ap.add_argument("--object", default=None)
|
||
ap.add_argument("--uv", type=float, nargs=2, default=None, help="原图像素坐标,覆盖 --object")
|
||
ap.add_argument("--perceive", action="store_true", help="物体像素取自点云感知(perception.json)而非仿真真值(camera.json)")
|
||
ap.add_argument("--num", type=int, default=16); ap.add_argument("--steps", type=int, default=1)
|
||
ap.add_argument("--checkpoint", default=str(configured_path('HUG_CHECKPOINT', configured_path('HUG_ROOT', 'external/hug') / 'checkpoints/hug_full.safetensors')))
|
||
ap.add_argument("--seed", type=int, default=0)
|
||
a = ap.parse_args()
|
||
cap = Path(a.capture).expanduser().resolve()
|
||
cam = json.loads((cap / "camera.json").read_text())
|
||
if a.uv is not None:
|
||
uv = np.array(a.uv, float); tag = f"uv{int(uv[0])}_{int(uv[1])}"
|
||
elif a.perceive:
|
||
perc = json.loads((cap / "perception.json").read_text())
|
||
if a.object not in perc["objects"]:
|
||
print(f"PERCEPTION_MISS {a.object} (detected {list(perc['objects'])}, missing {perc.get('missing')})")
|
||
sys.exit(3)
|
||
uv = np.array(perc["objects"][a.object]["uv"], float); tag = a.object
|
||
else:
|
||
assert a.object in cam["objects"], f"unknown object {a.object}; have {list(cam['objects'])}"
|
||
uv = np.array(cam["objects"][a.object]["uv"], float); tag = a.object
|
||
|
||
from hug.prepare_inputs import prepare_pkl, _load_intrinsics, _read_rgb, _read_depth_uint16
|
||
from hug.inference import load_model
|
||
from hug.dataloader.grasp_dataset import GraspDataset
|
||
from hug.models.mano import mano_params_to_grasp_dict
|
||
from hug.utils.pcl_utils import pixel_to_xyz, depth_to_pcl_tensors
|
||
|
||
rgb = _read_rgb(cap / "rgb.png"); depth = _read_depth_uint16(cap / "depth.png"); K = _load_intrinsics(cap / "intrinsics.txt")
|
||
h, w = rgb.shape[:2]; size = min(h, w); x_off, y_off = (w - size) // 2, (h - size) // 2
|
||
stem = "capture"
|
||
prepare_pkl(rgb, depth, K, stem, cap, object_name=tag)
|
||
u224 = (uv[0] - x_off) * 224.0 / size; v224 = (uv[1] - y_off) * 224.0 / size
|
||
if not (0 <= u224 < 224 and 0 <= v224 < 224): # 物体被撞出画面/裁剪外:优雅跳过而非崩溃(GT 与感知两条路都受益)
|
||
print(f"OFFSCREEN {tag} uv={uv.round(1).tolist()} 在中心正方形裁剪之外(裁剪 x∈[{x_off},{x_off+size}))")
|
||
sys.exit(3)
|
||
|
||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||
torch.manual_seed(a.seed)
|
||
model = load_model(Path(a.checkpoint), True, device)
|
||
use_rgb = getattr(model, "use_rgb", True); use_depth = getattr(model, "use_depth", False); pcl_use_rgb = getattr(model, "pcl_use_rgb", False)
|
||
ds = GraspDataset(str(cap), split="val", use_rgb=use_rgb, use_depth=use_depth)
|
||
s = ds.get_inference_data(stem)
|
||
K224 = np.asarray(s["camera_K"]); dimg = s["depth_image"]
|
||
dh, dw = dimg.shape[:2]
|
||
depth_m = float(dimg[int(np.clip(v224 * dh / 224, 0, dh - 1)), int(np.clip(u224 * dw / 224, 0, dw - 1))]) / 1000.0
|
||
print(f"click {tag}: orig uv={uv.round(1).tolist()} -> 224 uv=({u224:.1f},{v224:.1f}) depth={depth_m:.3f} m; model use_rgb={use_rgb} use_depth={use_depth}")
|
||
N = a.num
|
||
point_uv = torch.tensor([[u224, v224, depth_m]], dtype=torch.float32, device=device).repeat(N, 1)
|
||
camK = torch.from_numpy(K224).float().unsqueeze(0).to(device).repeat(N, 1, 1)
|
||
rgb_t = s["rgb"].unsqueeze(0).to(device).repeat(N, 1, 1, 1) if use_rgb else None
|
||
pcl_xyz = pcl_rgb = None
|
||
if use_depth:
|
||
crop_r = getattr(model, "pcl_crop_radius", None)
|
||
if crop_r is not None:
|
||
xyz, prgb = depth_to_pcl_tensors(dimg.astype(np.float32) / 1000.0, s["rgb_original"], K224,
|
||
center=pixel_to_xyz(u224, v224, depth_m, K224), crop_radius=crop_r)
|
||
else:
|
||
xyz, prgb = s["pcl_xyz"], s["pcl_rgb"]
|
||
pcl_xyz = xyz.unsqueeze(0).to(device).repeat(N, 1, 1)
|
||
pcl_rgb = prgb.unsqueeze(0).to(device).repeat(N, 1, 1) if pcl_use_rgb else None
|
||
t0 = time.time()
|
||
with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16, enabled=(device == "cuda")):
|
||
preds = model.sample(point_uv, camK, steps=a.steps, rgb=rgb_t, pcl_xyz=pcl_xyz, pcl_rgb=pcl_rgb)
|
||
print(f"sampled {N} grasps in {time.time() - t0:.2f}s")
|
||
betas = model.fixed_betas.squeeze(0)
|
||
T_wc = np.asarray(cam["T_world_cam_opencv"])
|
||
R_wc, t_wc = T_wc[:3, :3], T_wc[:3, 3]
|
||
out = {k: [] for k in ("landmarks_cam", "T_cam_wrist", "pose_aa", "verts_cam")}
|
||
for i in range(N):
|
||
g = mano_params_to_grasp_dict(preds[i].float(), betas, model.mano, K224, model.mesh_faces)
|
||
out["landmarks_cam"].append(np.asarray(g["landmarks_3d"])); out["T_cam_wrist"].append(np.asarray(g["T_camera_wrist"]))
|
||
out["pose_aa"].append(np.asarray(g["pose"]).reshape(15, 3)); out["verts_cam"].append(np.asarray(g["mesh_vertices"]))
|
||
out = {k: np.stack(v) for k, v in out.items()}
|
||
out["landmarks_world"] = out["landmarks_cam"] @ R_wc.T + t_wc
|
||
out["verts_world"] = out["verts_cam"] @ R_wc.T + t_wc
|
||
out["T_world_wrist"] = np.einsum("ij,njk->nik", T_wc, out["T_cam_wrist"])
|
||
click_cam = pixel_to_xyz(u224, v224, depth_m, K224)
|
||
out["click_world"] = R_wc @ np.asarray(click_cam, float) + t_wc
|
||
out["click_uv_orig"] = uv; out["K224"] = K224; out["T_world_cam"] = T_wc
|
||
out["mesh_faces"] = np.asarray(model.mesh_faces)
|
||
path = cap / f"hug_{tag}.npz"; np.savez(path, **out)
|
||
d = np.linalg.norm(out["landmarks_world"][:, 0] - out["click_world"], axis=1)
|
||
print(f"wrote {path}; click world={out['click_world'].round(3).tolist()}; wrist-to-click dist: min {d.min()*100:.1f} cm, median {np.median(d)*100:.1f} cm")
|
||
for i in range(min(N, 5)):
|
||
print(f" #{i}: wrist world={out['landmarks_world'][i,0].round(3).tolist()} palm-z(指向)={out['T_world_wrist'][i][:3,2].round(2).tolist()}")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|