SpineDepth_perframe / reconstruct_frames.py
luohwu's picture
Add SpineDepth per-frame raw data, reconstruction script and README (part 9)
642910b verified
Raw History Blame Contribute Delete
9.77 kB
"""
reconstruct_frames.py - rebuild per-frame point clouds from the SpineDepth raw data.
Usage (run from anywhere; paths default to the folder that contains this script):
python reconstruct_frames.py # specimen 2 (default)
python reconstruct_frames.py --specimen 5 # one specimen
python reconstruct_frames.py --specimen all # all ten specimens
python reconstruct_frames.py --specimen 3 --workers 8 --out-root D:/somewhere
Requirements: Python >= 3.8, numpy, open3d >= 0.15 (pip install -r requirements.txt)
Tested on Windows 10 (Python 3.x); uses only os.path, so Linux/macOS work the same.
Raw input layout (shipped in ./raw):
raw/Specimen_N/STL/L1.stl ... L5.stl
raw/Specimen_N/recordings/recordingR/Poses_0.txt, Poses_1.txt
raw/Specimen_N/recordings/recordingR/Specimen_N_recording_R_cam_C_frame_F.npz
Each npz holds an (M, 7) float64 array: x, y, z, r, g, b, label
(label 0 = background, 1..5 = L1..L5; xyz in millimetres, camera space; rgb in [0, 1]).
Poses_C.txt has 5 rows per video frame (L1..L5); each row is a flattened 4x4
matrix T (row-major, 16 comma-separated values) with p_camera = T @ p_ct.
Frame F of an npz uses pose rows F*5 .. F*5+4.
Output layout (written to ./reconstructed by default; every point-cloud file
name states its coordinate space):
reconstructed/
index.csv all reconstructed specimens
Specimen_N/
index.csv this specimen only
CT/L1.stl ... L5.stl CT vertebra meshes, each in its own CT space
camera_C/recording_RR/frame_F/
frame_camera_space.ply full raw frame, camera space, RGB
frame_camera_space_labels.npy int8 label per point of the file above
poses_ct_to_camera.txt 5 rows L1..L5, flattened 4x4, p_camera = T @ p_ct
L1_camera_space.ply ... L5_camera_space.ply points labelled Lk, camera space, RGB
L1_ct_space.ply ... L5_ct_space.ply same points moved into CT space of Lk
Nothing is filtered or downsampled; the label column is used as-is.
"""
import argparse
import csv
import os
import re
import shutil
import sys
from concurrent.futures import ProcessPoolExecutor
import numpy as np
import open3d as o3d
HERE = os.path.dirname(os.path.abspath(__file__))
LEVELS = [1, 2, 3, 4, 5]
ALL_SPECIMENS = list(range(1, 11))
FRAME_RE = re.compile(r"Specimen_(\d+)_recording_(\d+)_cam_(\d+)_frame_(\d+)\.npz$")
INDEX_HEADER = ["specimen", "camera", "recording", "frame", "level", "num_points_level",
"num_points_frame", "camera_space_ply", "ct_space_ply", "ct_mesh"]
def read_transformation_matrices(file_path):
"""Each line = 16 comma-separated floats = one 4x4 matrix (row-major)."""
matrices = []
with open(file_path, "r") as f:
for line in f:
line = line.strip()
if not line:
continue
values = list(map(float, line.split(",")))
if len(values) != 16:
raise ValueError(f"{file_path}: expected 16 values per line, got {len(values)}")
matrices.append(np.array(values).reshape(4, 4))
return matrices
def make_pcd(xyz, rgb=None):
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(xyz)
if rgb is not None and len(rgb):
pcd.colors = o3d.utility.Vector3dVector(rgb)
return pcd
def process_frame(task):
"""Worker: convert one npz frame. Returns index rows."""
specimen, cam, rec_idx, frame, npz_path, frame_poses, frame_out, out_root = task
os.makedirs(frame_out, exist_ok=True)
data = np.load(npz_path)["arr_0"]
if data.ndim != 2 or data.shape[1] < 7:
raise ValueError(f"{npz_path}: expected an (N, 7) array [x y z r g b label], got shape {data.shape}")
xyz = data[:, :3]
rgb = data[:, 3:6]
labels = data[:, 6].astype(np.int8)
o3d.io.write_point_cloud(os.path.join(frame_out, "frame_camera_space.ply"), make_pcd(xyz, rgb))
np.save(os.path.join(frame_out, "frame_camera_space_labels.npy"), labels)
np.savetxt(os.path.join(frame_out, "poses_ct_to_camera.txt"),
np.array([T.reshape(-1) for T in frame_poses]), fmt="%.9f", delimiter=",")
rows = []
for lv, T_ct_to_cam in zip(LEVELS, frame_poses):
sel = labels == lv
pcd_cam = make_pcd(xyz[sel], rgb[sel])
cam_ply = os.path.join(frame_out, f"L{lv}_camera_space.ply")
o3d.io.write_point_cloud(cam_ply, pcd_cam)
pcd_ct = make_pcd(xyz[sel], rgb[sel])
pcd_ct.transform(np.linalg.inv(T_ct_to_cam))
ct_ply = os.path.join(frame_out, f"L{lv}_ct_space.ply")
o3d.io.write_point_cloud(ct_ply, pcd_ct)
rows.append([specimen, cam, rec_idx, frame, lv, int(sel.sum()), len(xyz),
os.path.relpath(cam_ply, out_root).replace(os.sep, "/"),
os.path.relpath(ct_ply, out_root).replace(os.sep, "/"),
f"Specimen_{specimen}/CT/L{lv}.stl"])
return rows
def build_tasks(raw_root, out_root, specimen):
spec_in = os.path.join(raw_root, f"Specimen_{specimen}")
spec_out = os.path.join(out_root, f"Specimen_{specimen}")
rec_dir = os.path.join(spec_in, "recordings")
if not os.path.isdir(rec_dir):
print(f"[skip] {spec_in}: no recordings folder")
return []
ct_out = os.path.join(spec_out, "CT")
os.makedirs(ct_out, exist_ok=True)
for lv in LEVELS:
shutil.copy2(os.path.join(spec_in, "STL", f"L{lv}.stl"), os.path.join(ct_out, f"L{lv}.stl"))
tasks = []
recordings = sorted((d for d in os.listdir(rec_dir) if d.startswith("recording")),
key=lambda d: int(d[len("recording"):]))
for rec_name in recordings:
rec_path = os.path.join(rec_dir, rec_name)
rec_idx = int(rec_name[len("recording"):])
frame_files = sorted(f for f in os.listdir(rec_path) if FRAME_RE.match(f))
if not frame_files:
continue
poses = {}
for f in frame_files:
m = FRAME_RE.match(f)
cam, frame = int(m.group(3)), int(m.group(4))
if cam not in poses:
poses[cam] = read_transformation_matrices(os.path.join(rec_path, f"Poses_{cam}.txt"))
first = frame * 5
if first + 5 > len(poses[cam]):
print(f"[warn] {f}: pose rows {first}..{first + 4} missing, frame skipped")
continue
frame_poses = poses[cam][first:first + 5]
frame_out = os.path.join(spec_out, f"camera_{cam}", f"recording_{rec_idx:02d}", f"frame_{frame}")
tasks.append((specimen, cam, rec_idx, frame, os.path.join(rec_path, f), frame_poses, frame_out, out_root))
return tasks
def write_index(path, rows):
with open(path, "w", newline="") as fh:
w = csv.writer(fh)
w.writerow(INDEX_HEADER)
w.writerows(rows)
def parse_specimen(value):
if value.lower() == "all":
return ALL_SPECIMENS
try:
s = int(value)
except ValueError:
raise argparse.ArgumentTypeError(f"--specimen must be 'all' or an integer 1..10, got {value!r}")
if s not in ALL_SPECIMENS:
raise argparse.ArgumentTypeError(f"--specimen must be 'all' or an integer 1..10, got {s}")
return [s]
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--specimen", type=parse_specimen, default="2",
help="'all' or a specimen index 1..10 (default: 2)")
ap.add_argument("--raw-root", default=os.path.join(HERE, "raw"), help="folder with Specimen_N/ raw data")
ap.add_argument("--out-root", default=os.path.join(HERE, "reconstructed"), help="output folder")
ap.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 2) // 2),
help="parallel worker processes (default: half the CPU cores)")
args = ap.parse_args()
specimens = args.specimen if isinstance(args.specimen, list) else parse_specimen(args.specimen)
if not os.path.isdir(args.raw_root):
sys.exit(f"raw root not found: {args.raw_root}")
os.makedirs(args.out_root, exist_ok=True)
print(f"raw: {args.raw_root}\nout: {args.out_root}\nspecimens: {specimens}\nworkers: {args.workers}", flush=True)
with ProcessPoolExecutor(max_workers=args.workers) as pool:
for s in specimens:
tasks = build_tasks(args.raw_root, args.out_root, s)
if not tasks:
continue
rows = []
for i, r in enumerate(pool.map(process_frame, tasks, chunksize=2), 1):
rows += r
if i % 40 == 0 or i == len(tasks):
print(f"Specimen_{s}: {i}/{len(tasks)} frames", flush=True)
rows.sort(key=lambda r: r[:5])
write_index(os.path.join(args.out_root, f"Specimen_{s}", "index.csv"), rows)
print(f"Specimen_{s}: wrote {len(rows)} vertebra clouds", flush=True)
# Root index = union of every per-specimen index present on disk.
all_rows = []
for d in sorted(os.listdir(args.out_root),
key=lambda d: int(d.split("_")[1]) if d.startswith("Specimen_") else -1):
p = os.path.join(args.out_root, d, "index.csv")
if d.startswith("Specimen_") and os.path.isfile(p):
with open(p, newline="") as fh:
all_rows += list(csv.reader(fh))[1:]
write_index(os.path.join(args.out_root, "index.csv"), all_rows)
print(f"Done: root index has {len(all_rows)} vertebra clouds.")
if __name__ == "__main__":
main()