yayalong's picture
Add files using upload-large-folder tool
21e1acb verified
Raw
History Blame Contribute Delete
4.57 kB
"""GraspGen-style PCA/AABB grasp prior for ATEC Task E.
This mirrors the core idea used by the PiPER GraspGen demo: reconstruct the
segmented RGB-D points, run PCA, build an oriented AABB, and use its center as a
geometric grasp prior. The Task-E runner may still override orientation with
the calibrated Piper quaternion.
"""
from __future__ import annotations
import numpy as np
from scipy.spatial.transform import Rotation
from scripts.graspnet_task_e.tuntun_adapter import TaskEGrasp, camera_arrays
def _masked_world_points(camera, mask: np.ndarray) -> np.ndarray:
_rgb, depth, K, pos_w, quat_wxyz_ros = camera_arrays(camera)
valid = (mask > 0) & np.isfinite(depth) & (depth > 0.0) & (depth < 6.0)
if not np.any(valid):
raise RuntimeError("No valid masked depth points for PCA/AABB grasp.")
ys, xs = np.where(valid)
z = depth[ys, xs].astype(np.float64)
x = (xs.astype(np.float64) - float(K[0, 2])) / float(K[0, 0]) * z
y = (ys.astype(np.float64) - float(K[1, 2])) / float(K[1, 1]) * z
pts_cam = np.stack([x, y, z], axis=1)
rot_w_cam = Rotation.from_quat(
[quat_wxyz_ros[1], quat_wxyz_ros[2], quat_wxyz_ros[3], quat_wxyz_ros[0]]
).as_matrix()
return (rot_w_cam @ pts_cam.T).T + pos_w
def _pca_aabb(points_w: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, int]:
pts = np.asarray(points_w, dtype=np.float64)
if pts.shape[0] < 4:
raise RuntimeError("Too few points for PCA/AABB grasp.")
centroid = np.mean(pts, axis=0)
centered = pts - centroid
covariance = (centered.T @ centered) / max(centered.shape[0] - 1, 1)
eigen_values, eigen_vectors = np.linalg.eigh(covariance)
ev = eigen_vectors.copy()
ev[:, 2] = np.cross(ev[:, 0], ev[:, 1])
ev[:, 1] = np.cross(ev[:, 2], ev[:, 0])
ev[:, 0] = np.cross(ev[:, 1], ev[:, 2])
for i in range(3):
norm = np.linalg.norm(ev[:, i])
if norm > 1e-10:
ev[:, i] /= norm
order = np.argsort(eigen_values)[::-1]
R = ev[:, order].copy()
if np.linalg.det(R) < 0:
R[:, 2] = -R[:, 2]
local = (R.T @ (pts - centroid).T).T
min_pt = np.min(local, axis=0)
max_pt = np.max(local, axis=0)
extents = max_pt - min_pt
center_local = (min_pt + max_pt) * 0.5
center_w = R @ center_local + centroid
grasp_axis = int(np.argmin(extents))
return center_w.astype(np.float64), R.astype(np.float64), extents.astype(np.float64), grasp_axis
def infer_pca_aabb_from_camera(camera, mask: np.ndarray, object_index: int | None = None) -> TaskEGrasp:
"""Return a GraspGen-style geometric grasp prior from segmented RGB-D."""
pts_w = _masked_world_points(camera, mask)
# Use the visible object body. Box/bottle masks are most stable with the
# upper visible surface median, while the banana's curved mask is less
# stable there and works better from the oriented AABB center.
center_w, R_pca, extents, grasp_axis = _pca_aabb(pts_w)
z_gate = float(np.percentile(pts_w[:, 2], 70))
upper = pts_w[pts_w[:, 2] >= z_gate]
exec_center = center_w.copy()
if object_index != 3 and len(upper) > 16:
exec_center[:2] = np.median(upper[:, :2], axis=0)
exec_center[2] = float(np.percentile(pts_w[:, 2], 85))
if grasp_axis == 0:
jaw_hint_w = R_pca[:, 1]
elif grasp_axis == 1:
jaw_hint_w = R_pca[:, 0]
else:
jaw_hint_w = R_pca[:, 0]
jaw_xy = np.array([jaw_hint_w[0], jaw_hint_w[1], 0.0], dtype=np.float64)
if np.linalg.norm(jaw_xy) < 1e-6:
jaw_xy = np.array([0.0, 1.0, 0.0], dtype=np.float64)
jaw_xy /= np.linalg.norm(jaw_xy)
grip_z = np.array([0.0, 0.0, -1.0], dtype=np.float64)
align_x = np.cross(jaw_xy, grip_z)
align_x /= max(np.linalg.norm(align_x), 1e-6)
jaw_y = np.cross(grip_z, align_x)
jaw_y /= max(np.linalg.norm(jaw_y), 1e-6)
R_w_tool = np.stack([align_x, jaw_y, grip_z], axis=1)
quat_xyzw = Rotation.from_matrix(R_w_tool).as_quat()
quat_wxyz = np.array([quat_xyzw[3], quat_xyzw[0], quat_xyzw[1], quat_xyzw[2]], dtype=np.float64)
width = float(extents[grasp_axis])
score = 1.0 / (1.0 + float(np.linalg.norm(extents)))
print(
f"[PCA_AABB] points={len(pts_w)} extents=({extents[0]:.3f},{extents[1]:.3f},{extents[2]:.3f}) "
f"axis={grasp_axis} width={width:.3f}"
)
return TaskEGrasp(
translation_w=exec_center.astype(np.float64),
quat_wxyz_w=quat_wxyz,
score=score,
width=width,
raw_translation_cam=np.zeros(3, dtype=np.float64),
)