OmniRooms / original /process_cube_sampling.py
Insta360-Research's picture
Add files using upload-large-folder tool
d0aefab verified
Raw
History Blame
7.48 kB
#!/usr/bin/env python3
import argparse
import csv
import random
from pathlib import Path
def format_one_decimal(value: float) -> str:
return f"{value:.1f}"
def random_point_in_cube(cx: float, cy: float, cz: float, half_edge: float) -> tuple[float, float, float]:
return (
cx + random.uniform(-half_edge, half_edge),
cy + random.uniform(-half_edge, half_edge),
cz + random.uniform(-half_edge, half_edge),
)
def random_point_in_cube_with_z_limits(
cx: float,
cy: float,
cz: float,
half_edge: float,
z_min: float,
z_max: float,
) -> tuple[float, float, float]:
z_low = max(cz - half_edge, z_min)
z_high = min(cz + half_edge, z_max)
if z_low > z_high:
raise ValueError(f"非法的 Z 采样区间: [{z_low}, {z_high}]")
return (
cx + random.uniform(-half_edge, half_edge),
cy + random.uniform(-half_edge, half_edge),
random.uniform(z_low, z_high),
)
def process_file(
path: Path,
mode: str,
edge_cm: float,
points_per_group: int,
seed: int | None,
z_min: float,
z_max: float,
extract_centers_every: int,
output_dir: Path | None = None,
) -> None:
if seed is not None:
random.seed(seed)
half_edge = edge_cm / 2.0
# 确定输出文件的路径
if output_dir is None:
# 原有行为:写临时文件然后替换原文件
out_path = path.with_suffix(path.suffix + ".tmp")
replace_original = True
else:
# 输出到指定目录,不覆盖原文件
out_path = output_dir / path.name
replace_original = False
with path.open("r", newline="", encoding="utf-8") as src, out_path.open(
"w", newline="", encoding="utf-8"
) as dst:
reader = csv.DictReader(src)
fieldnames = reader.fieldnames
if not fieldnames:
raise ValueError(f"CSV 表头为空: {path}")
if not {"X", "Y", "Z"}.issubset(set(fieldnames)):
raise ValueError(f"缺少 X/Y/Z 列: {path}")
index_col = fieldnames[0]
writer = csv.DictWriter(dst, fieldnames=fieldnames, lineterminator="\n")
writer.writeheader()
out_index = 1
in_count = 0
center_count = 0
kept_center_count = 0
for row_idx, row in enumerate(reader):
in_count += 1
# 当输入已经是“每组30条”时,仅抽取每组第一条作为中心点
if mode == "zrange-expand" and extract_centers_every > 1 and (row_idx % extract_centers_every != 0):
continue
center_count += 1
cx = float(row["X"])
cy = float(row["Y"])
cz = float(row["Z"])
if mode == "normalize":
points = [(cx, cy, cz)]
elif mode == "expand":
points = [(cx, cy, cz)]
for _ in range(points_per_group - 1):
points.append(random_point_in_cube(cx, cy, cz, half_edge))
else:
# 仅保留 z 在 [z_min, z_max] 的中心点
if not (z_min <= cz <= z_max):
continue
kept_center_count += 1
points = [(cx, cy, cz)]
for _ in range(points_per_group - 1):
points.append(
random_point_in_cube_with_z_limits(
cx=cx,
cy=cy,
cz=cz,
half_edge=half_edge,
z_min=z_min,
z_max=z_max,
)
)
for x, y, z in points:
new_row = dict(row)
new_row[index_col] = str(out_index)
new_row["X"] = format_one_decimal(x)
new_row["Y"] = format_one_decimal(y)
new_row["Z"] = format_one_decimal(z)
writer.writerow(new_row)
out_index += 1
if replace_original:
out_path.replace(path)
if mode == "zrange-expand":
print(
f"{path.name}: in={in_count}, centers={center_count}, kept_centers={kept_center_count}, out={out_index - 1}"
)
else:
print(f"{path.name}: in={in_count}, out={out_index - 1}")
def main() -> None:
parser = argparse.ArgumentParser(
description="按立方体随机采样扩增 CSV,或仅格式化/重排索引。"
)
parser.add_argument(
"--dir",
default="/media/team_data/ML4_team/datasets/smx_sim/original",
help="输入 CSV 目录路径。",
)
parser.add_argument(
"--mode",
choices=["expand", "normalize", "zrange-expand"],
default="zrange-expand",
help="expand: 每条扩成一组; normalize: 仅重排索引; zrange-expand: 按Z范围筛选中心点后扩增。",
)
parser.add_argument(
"--edge-cm",
type=float,
default=30.0,
help="立方体边长(厘米),默认 30。",
)
parser.add_argument(
"--points-per-group",
type=int,
default=30,
help="每组点数(中心点+随机点),默认 30。",
)
parser.add_argument(
"--seed",
type=int,
default=None,
help="可选随机种子,便于复现。",
)
parser.add_argument(
"--z-min",
type=float,
default=60.0,
help="zrange-expand 模式下,中心点与生成点的最小 Z。",
)
parser.add_argument(
"--z-max",
type=float,
default=180.0,
help="zrange-expand 模式下,中心点与生成点的最大 Z。",
)
parser.add_argument(
"--extract-centers-every",
type=int,
default=1,
help="zrange-expand 模式下,从输入中每 N 条抽取 1 条作为中心点;输入若是旧的30倍数据可设为30。",
)
parser.add_argument(
"--output-dir",
type=str,
default="/media/team_data/ML4_team/datasets/smx_sim/30cm",
help="输出目录,结果将写入该目录,不覆盖原文件。",
)
args = parser.parse_args()
target_dir = Path(args.dir).resolve()
csv_files = sorted(target_dir.glob("*.csv"))
if not csv_files:
raise FileNotFoundError(f"目录下未找到 CSV: {target_dir}")
if args.mode == "expand" and args.points_per_group < 1:
raise ValueError("points-per-group 必须 >= 1")
if args.mode == "zrange-expand":
if args.points_per_group < 1:
raise ValueError("points-per-group 必须 >= 1")
if args.z_min > args.z_max:
raise ValueError("z-min 不能大于 z-max")
if args.extract_centers_every < 1:
raise ValueError("extract-centers-every 必须 >= 1")
output_dir = Path(args.output_dir).resolve() if args.output_dir else None
if output_dir and not output_dir.exists():
output_dir.mkdir(parents=True, exist_ok=True)
for csv_file in csv_files:
process_file(
path=csv_file,
mode=args.mode,
edge_cm=args.edge_cm,
points_per_group=args.points_per_group,
seed=args.seed,
z_min=args.z_min,
z_max=args.z_max,
extract_centers_every=args.extract_centers_every,
output_dir=output_dir,
)
if __name__ == "__main__":
main()