Datasets:
File size: 7,477 Bytes
d0aefab | 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 | #!/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() |