本页从故障记录中分离通用知识与示例。本轮没有重跑示例或重新核验外部接口;下述运行声明属于此前整理。
完整的输入校验示例
跳转到“完整的输入校验示例”下面的独立程序保留“读类别清单 → Open3D 读 PCD → Torch 张量 → FPS 索引 → 毫米转米”的流程。它默认遇到缺失或坏数据就报错,避免跳过类别后使列表索引与标签错位。read_points 参数便于用明确的测试数据核对边界。
from pathlib import Pathimport argparseimport numpy as npimport torch
def farthest_point_sample(xyz, npoint): if not isinstance(xyz, torch.Tensor) or xyz.dtype not in ( torch.float16, torch.bfloat16, torch.float32, torch.float64): raise TypeError("xyz must be a real floating-point tensor") if xyz.ndim != 3 or xyz.shape[0] == 0 or xyz.shape[2] != 3: raise ValueError("xyz must have shape (B, N, 3), with B > 0") batch_size, count, _ = xyz.shape if isinstance(npoint, bool) or not isinstance(npoint, int): raise TypeError("npoint must be an integer") if count == 0 or not 1 <= npoint <= count: raise ValueError("require 1 <= npoint <= N and N > 0") if not torch.isfinite(xyz).all(): raise ValueError("coordinates must be finite") # Double precision prevents squaring large float32 values from overflowing. points = xyz.to(dtype=torch.float64) if (points.abs() > torch.finfo(torch.float32).max).any(): raise ValueError("coordinates must be within float32 magnitude") indices = torch.empty((batch_size, npoint), dtype=torch.long, device=xyz.device) distances = torch.full((batch_size, count), float("inf"), dtype=torch.float64, device=xyz.device) selected = torch.zeros((batch_size, count), dtype=torch.bool, device=xyz.device) batches = torch.arange(batch_size, device=xyz.device) farthest = torch.randint(0, count, (batch_size,), device=xyz.device) for step in range(npoint): indices[:, step] = farthest selected[batches, farthest] = True center = points[batches, farthest, :].unsqueeze(1) squared = ((points - center) ** 2).sum(dim=2) distances = torch.minimum(distances, squared) farthest = distances.masked_fill(selected, -1).argmax(dim=1) return indices
def read_pcd(path): import open3d as o3d input_cloud = o3d.io.read_point_cloud(str(path)) return np.asarray(input_cloud.points)
def load_class_clouds(class_list, root, num_pt, read_points=read_pcd): names, clouds = [], [] with Path(class_list).open(encoding="utf-8") as class_file: for line_number, class_input in enumerate(class_file, start=1): name = class_input.strip() if not name: continue if name in {".", ".."} or "/" in name or "\\" in name: raise ValueError(f"invalid class name on line {line_number}") if name in names: raise ValueError(f"duplicate class: {name}") file = Path(root) / "models" / f"{name}.pcd" if not file.is_file(): raise FileNotFoundError(f"class {name}: {file}") points = np.asarray(read_points(file)) if points.ndim != 2 or points.shape[1] != 3 or len(points) == 0: raise ValueError(f"class {name}: expected nonempty (N, 3)") if points.dtype.kind not in "fiu" or not np.isfinite(points).all(): raise ValueError(f"class {name}: expected finite real coordinates") with np.errstate(over="ignore", invalid="ignore"): points = points.astype(np.float32) if not np.isfinite(points).all(): raise ValueError(f"class {name}: coordinates exceed float32") raw_xyz = torch.tensor(points.reshape((1, -1, 3)), dtype=torch.float32) xyz_ids = farthest_point_sample(raw_xyz, num_pt).cpu().numpy() raw_xyz = points * np.float32(0.001) names.append(name) clouds.append(raw_xyz[xyz_ids[0, :], :]) if not names: raise ValueError("class list contains no model names") return names, clouds
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("class_list") parser.add_argument("root") parser.add_argument("--num-points", type=int, default=1024) args = parser.parse_args() names, clouds = load_class_clouds(args.class_list, args.root, args.num_points) print([(name, cloud.shape) for name, cloud in zip(names, clouds)])直接调用 farthest_point_sample 也要求实数浮点张量,坐标幅度不超过 float32 的有限范围;先转换到 float64 再计算距离,不能解释为任意有限 float64 坐标的平方都不会溢出。对全零或重复坐标,示例保证选取不同索引,不保证坐标各异;随机起点也意味着不同运行不必返回同一组索引。
环境中需要 NumPy、PyTorch;真正读取 PCD 时还需要 Open3D。在相应数据目录运行 python load_clouds.py classes.txt ./datasets/tless --num-points 1024。这里的参数文件名是示例,必须对应实际数据集。
本文参考 FPS 实现用于说明有效输入与索引边界,不声称与 ES6D 原项目的所有采样细节相同。此前内容整理在 Linux Python 3.12、NumPy 2.3.5、PyTorch 2.8.0 CPU 中检查合成点云;另用 Open3D 0.19.0 读取自建 ASCII PCD 文件。没有取得原始 ES6D 数据,也没有运行完整训练或 GPU 路径。
接口依据:torch.randint、Open3D read_point_cloud。
来源:CSDN 原文,首次发布于 2024-05-24。