Skip to content

About

Script to automate Cloud Compare processes; part of the Tharros Archaeological Research Project (TARP).

Resources

Stars

1 star

Watchers

0 watching

Forks

 
 

Latest commit

 

History

124 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CloudCompare Script — Automated SU Volume Extraction

Part of the Tharros Archaeological Research Project (TARP) · SU Sheet Builder →


The Problem

iPhone LiDAR (annotated) Photogrammetry PLY
LiDAR scan with yellow SU annotation Photogrammetry PLY model

Trench supervisors at Tharros use iPad LiDAR to mark each Stratigraphic Unit (SU) by painting the excavated surface yellow. The photogrammetry jobs — GPS-referenced, drone-quality 3D models — are far higher quality but carry no annotations. To compute SU volumes for the SU Sheet, we need to transfer the annotation across.

Before this pipeline, that meant manually locating the LiDAR annotation in CloudCompare, clipping the SU out of the photogrammetry job, and computing the before/after volume difference — 15–30 minutes per SU. With 200+ SUs per season and a 3–5 year backlog, that adds up fast.

The goal: fully automated LiDAR-to-photogrammetry annotation transfer, producing volumes like these:

Extracted SU volumes


Why It's Hard

No GPS on the LiDAR. Each supervisor scans freehand from wherever they're standing. The iPhone coordinate frame is arbitrary and different every time — standard ICP requires a rough manual alignment first, which defeats the purpose.

Partial, asymmetric coverage. The LiDAR might catch only a corner of the trench at an oblique angle. The photogrammetry covers the full site from above. Neither is a subset of the other.

Metric drift. iPhone LiDAR has ~2–3% scale error relative to the georeferenced photogrammetry. Any registration has to recover or absorb that.

No training data. The yellow paint sits on top of the excavated surface, destroying the underlying texture in the LiDAR. We can't extract before/after pairs to build a supervised dataset. One-shot it is.

Manual CloudCompare setup before any snip can happen. Before you can crop a single SU, you have to: load the top and bottom PLY meshes, sample them to dense point clouds, compute bidirectional cloud-to-cloud distances (choosing local model, octree level, and search radius), and save tagged .bin files — all done by hand in CloudCompare's GUI, repeated for every job pair. With dozens of photogrammetry jobs per season, this alone was a significant time sink before the crop even started.

Poisson reconstruction produces bubbles and holes — every time. Merging two open surfaces (top and bottom of the SU) and running Poisson reconstruction sounds straightforward, but in practice it consistently generated bubble volumes at the SU rim (where the two surfaces nearly meet) and phantom faces at the mesh boundary. The only way to fix them was to tweak Poisson depth, density threshold, and the C2C filter cutoff by hand, then inspect the result visually, adjust again, and repeat. Every SU had different geometry so there was no single setting that worked. Not scalable to 200+ SUs.


The Pipeline

Three scripts, one JSON config:

input.json → pre_snip_script.py → auto_snip_script.py → post_snip_script.py → volume_measures.txt
Step Script What it does
1 · Pre-snip pre_snip_script.py Load PLY meshes, sample to point clouds, compute bidirectional C2C distances
2 · Auto-snip auto_snip_script.py Register the LiDAR annotation to the PLY world frame; crop both clouds to the SU boundary
3 · Post-snip post_snip_script.py Merge cropped clouds, reconstruct surface, compute volumes

Step 1 — Pre-snip

./run.sh pre_snip_script.py input.json

Loads paired top and bottom PLY photogrammetry meshes, samples them to point clouds, and computes bidirectional cloud-to-cloud (C2C) distances — top→bottom and bottom→top — tagged on each cloud as scalar fields.

Why bidirectional? The C2C distance from a point on the top surface to the bottom cloud is large where the layer is thick and small where the two surfaces nearly touch at the SU boundary rim. That distance field is used downstream by post-snip to filter out fringe points that would otherwise cause Poisson reconstruction to close over the rim with a bubble volume.

Local model: QUADRIC (octree level 7). Rather than measuring point-to-nearest-point distance, the algorithm fits a quadric surface to the local neighborhood of each reference point and measures distance to that surface. This recovers the true geometric distance even where point density varies — more accurate than a flat LS plane fit, especially on curved excavation walls and stone courses.

Output: Data/<top_job_folder>/*_top_with_dist_*.bin and *_bottom_with_dist_*.bin — CloudCompare binary clouds with the C2C scalar field embedded.


Step 2 — Auto-snip

./run.sh auto_snip_script.py input.json

The hard part: finding where the yellow-painted LiDAR annotation lands in the photogrammetry world frame. Two modes — autosnip (iPhone LiDAR USDZ) and manual snip (annotated PNG ortho).

What We Tried — and Why It Failed

Vision LLMs (Claude Haiku, GPT-4o, Gemini 2.5)

We rendered both the LiDAR and the PLY as top-down images and asked models to localise the matching region. Mean centroid error: 1.4–1.8 m. Competitive with classical methods but inconsistent and expensive — the rendered orthos don't have enough visual anchors, and there's no failure signal when the model hallucinates.

Claude Haiku Vision result on SU 20005 Claude Haiku Vision: 2.34 m error, IoU 0.08 — the model localises the general area but can't pin down the boundary precisely from rendered ortho images.

Classical Top-Cloud Methods

The idea: project both point clouds to 2D and align their footprints using PCA, phase correlation, or AKAZE feature matching.

dist_pca result on SU 20005 Left: LiDAR scan with yellow annotation (SU 20005) · Right: dist_pca placed result (green) — 0.84 m off, IoU 0.05. Distance-weighted PCA finds the right general area but gets the rotation wrong because the principal axes of the LiDAR point distribution (a free-form freehand scan) don't match those of the rectangular photogrammetry coverage — the two data distributions have different shapes, so their dominant directions disagree.

Best result: rgb_pca at 1.30 m mean centroid error. Phase correlation (2.56 m), AKAZE (2.63 m), and Chamfer (2.86 m) were worse.

The shared failure mode: all of these compare the LiDAR against the pre-excavation surface. The trench depression that makes each SU geometrically distinctive doesn't exist in the top cloud — it was dug after that photo session.

The Solution — Bottom DEM Slope-Map Correlation

Not yet validated end-to-end on the tarp-lab SU Sheet. The bottom_demcorr accuracy numbers below come from the standalone eval. In the SU Sheet pipeline we were incorrectly not passing the bottom pgram DEM, so this solution has not been exercised against live SU Sheet data yet. The bottom-DEM staging fix has since landed — a real SU Sheet run is still needed to confirm the numbers hold there.

Match the LiDAR against the bottom photogrammetry surface instead. The LiDAR is taken post-excavation, so it sees the same walls, stone courses, and floor features as the bottom PLY job.

Step 1 — Convert both to slope maps.

LiDAR slope map PLY bottom slope map
LiDAR slope map PLY bottom slope map

Slope maps (Sobel gradient of the height map) remove the elevation datum difference between sensors while preserving the geometrically distinctive structure: walls, steps, stone blocks.

Step 2 — Exhaustive sweep + FFT correlation.

Sweep yaw 0–360° and scale 0.95–1.05 (covering iPhone LiDAR metric drift). At each pose, find the best XY translation in O(N log N) via masked normalised cross-correlation (Padfield 2011) — only cells observed by both sensors are scored, so partial coverage doesn't throw off the result.

NCC score vs yaw angle — sharp peak at 148° NCC score vs yaw for SU 20005 — single dominant peak at 148°, peak-to-noise ratio 1.69×. High ratio = high confidence.

Step 3 — Apply the best pose.

bottom_demcorr result — 0.34 m error on SU 20005 Left: LiDAR annotation (SU 20005) · Right: bottom_demcorr placed result — 0.34 m centroid error vs manually drawn ground truth polygons, IoU 0.67

Crosscheck: manually drawn ground truth polygons showing where the annotation should land vs placed result on PLY ortho, SU 20005 Crosscheck on the PLY ortho: manually drawn ground truth polygons showing where the annotation should land (left) vs algorithm-placed polygon (magenta, right) — correct placement within the courtyard

Results across 4 sites

Centroid error measured against manually drawn ground truth polygons — hand-annotated on the PLY ortho to mark exactly where each SU annotation should land.

Site rgb_pca (previous best) bottom_demcorr IoU
SU 20002 1.26 m 0.48 m 0.59
SU 20003 1.30 m 0.46 m 0.61
SU 20005 (shown above) 1.30 m 0.34 m 0.67
SU 21001 1.30 m 0.34 m 0.78
Mean 1.30 m 0.41 m 0.66

3× improvement. No manual intervention.

Algorithmic complexity

The dominant cost is the coarse sweep: 180 yaw angles × 11 scale values = 1,980 FFT-NCC evaluations, each O(N log N) over ~90k DEM cells at 4 cm resolution.

Pass Angles Scales Cell size Time
Coarse 180 (2° step) 11 (0.95–1.05) 4 cm ~35 s
Refine 25 (0.25° step, ±3° window) 1 (fixed from coarse) 2 cm ~5 s

The LiDAR DEM is rasterised from mesh triangles using barycentric sampling (8×8 sub-samples per face), filling 84–98% of cells vs ~22% for vertex-only — critical for a usable slope map.

Mode A — Autosnip (USDZ)

For each USDZ annotation, the script:

  1. Loads the iPhone LiDAR scan and extracts the yellow-painted annotation polygon.
  2. Renders a top-down orthographic image of the PLY top cloud (1 cm/px, RGB colors from photogrammetry).
  3. Runs registration methods to align the LiDAR scan to the PLY world frame. rgb_pca is the default used for the crop; all methods save side-by-side debug composites.
  4. Transforms the yellow polygon to PLY world coordinates.
  5. Crops both clouds (top and bottom) to that polygon.
  6. Saves *_cleaned_su_<N>.bin files and debug images in Data/<json_id>/.

Registration methods (ranked by mean centroid error across 4 sites):

Method Mean error Notes
bottom_demcorr 0.41 m Slope-map masked NCC sweep vs bottom GeoTIFF DEM — best overall
rgb_pca (default crop) 1.30 m PCA on RGB footprints
dist_pca 1.34 m Distance-weighted PCA variant
phase_corr 2.56 m Phase correlation on Canny edges
prerot_akaze 2.63 m AKAZE — fails when LiDAR ≠ PLY texture
pca_chamfer 2.86 m PCA rotation + Chamfer translation

bottom_demcorr runs alongside top-cloud methods for debug/eval. The actual crop still uses rgb_pca — swap the default in run_autosnip() in auto_snip_script.py to promote it.

If rgb_pca gives the wrong result, inspect the other method debug images and re-run with the correct annotated ortho in manual snip mode.

Mode B — Manual Snip (PNG)

Draw the annotation as a black outline on the PLY top-down render (debug_topdown_render.png), then point input.json to that image:

[
  {
    "top": "786",
    "bottom": "787",
    "su": "20002",
    "annotations": ["orthos/ortho_20002_annotated.png"]
  }
]

The script detects black pixels, fills the enclosed region, and maps the polygon from ortho pixel space to PLY world coordinates.


Step 3 — Post-snip

./run.sh post_snip_script.py input.json

Turns a pair of cropped point clouds (top surface + bottom surface of the SU) into a watertight mesh and computes its volume. The main challenge: Poisson reconstruction fills gaps indiscriminately — without careful pre-processing it generates bubble volumes at the rim and phantom faces at the perimeter.

Algorithm:

  1. Invert bottom cloud normals. Before merging, normals on the bottom cloud are flipped to point inward (toward the volume interior). Without this, Poisson treats top and bottom as the same surface and produces an open shell instead of a closed volume.

  2. C2C distance filter (p25). The pre-snip scalar field gives each point its distance to the opposite surface. Points in the bottom 25th percentile — where the two surfaces nearly touch at the SU rim — are removed. This prevents Poisson from sealing the rim zone with a closed bubble volume that doesn't represent real excavated material.

  3. Poisson surface reconstruction (depth=11). High-depth reconstruction captures fine wall and floor detail. The density=True flag produces a per-vertex density scalar field alongside the mesh.

  4. Density trimming (p10). Faces at the 10th percentile of Poisson density are removed. These are phantom boundary faces that appear where the point cloud thins out at the perimeter — they sit outside the actual SU and inflate the volume if kept.

  5. Volume computation. Two measurements per SU:

    • 3D volume (cm³) — signed mesh volume from the watertight reconstructed surface
    • 2.5D projected volume (m³) — vertical distance integrated over the SU footprint area, robust to occlusions

Output: Data/Final_Volumes/SU_<N>_raw.obj and a line appended to volume_measures.txt.


Project Structure

cloudcomparescript/
├── pre_snip_script.py          # Step 1: distance computation
├── auto_snip_script.py         # Step 2: snipping (autosnip or manual)
├── auto_snip_lidar.py          # Registration library (all LiDAR methods)
├── post_snip_script.py         # Step 3: mesh generation and volume calculation
├── run.sh                      # Wrapper to run scripts with correct CloudComPy env
├── input.json                  # Canonical input — edit this for your run
├── example-*.json              # Per-site example configs
├── eval_methods.py             # Registration method evaluation script
├── volume_measures.txt         # Output volume measurements
└── Data/
    ├── Final_Volumes/          # Final SU volume meshes (OBJ)
    ├── eval/                   # eval_methods.py debug composites
    └── Pgram_Job_*/            # Per-job intermediate files and debug renders

Prerequisites

CloudCompare with Python Support (macOS Apple Silicon)

  1. Download the CloudComPy binary from openfields.fr — use the arm64 build.
  2. Extract to ~/Desktop/CloudComPy310_clean/ using ditto --norsrc (not a regular unzip) to strip macOS quarantine attributes:
    ditto --norsrc ~/Downloads/CloudComPy310_<date>.zip ~/Desktop/CloudComPy310_clean/
  3. Re-sign the Python binary to allow loading CloudComPy's libraries (required by macOS hardened runtime):
    cat > /tmp/cloudcompy_entitlements.plist << 'EOF'
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
        <true/>
        <key>com.apple.security.cs.disable-library-validation</key>
        <true/>
    </dict>
    </plist>
    EOF
    
    codesign --force --sign - --options runtime \
      --entitlements /tmp/cloudcompy_entitlements.plist \
      ~/miniconda3/envs/CloudComPy310/bin/python3.10

Conda Environment

conda create --name CloudComPy310 python=3.10
conda activate CloudComPy310
conda config --add channels conda-forge
conda config --set channel_priority flexible
conda install -y boost cgal cmake draco "ffmpeg=6.1" gdal jupyterlab laszip \
  matplotlib "mysql=8" notebook numpy opencv "openssl=3.1" pcl pdal psutil \
  pybind11 quaternion "qhull=2020.2" "qt=5.15.8" scipy sphinx_rtd_theme \
  spyder tbb tbb-devel "xerces-c=3.2" xorg-libx11

Running Scripts

Use run.sh (sets PYTHONPATH to include CloudComPy frameworks):

./run.sh pre_snip_script.py input.json
./run.sh auto_snip_script.py input.json
./run.sh post_snip_script.py input.json

All three scripts are also importable Python modules:

import pre_snip_script, auto_snip_script, post_snip_script

pre_snip_script.run_presnip_pipeline("input.json")
auto_snip_script.run_snip_pipeline("input.json")
post_snip_script.run_postsnip_pipeline("input.json")

Usage

Configure input.json

Place PLY files with naming convention Pgram_Job_<job_number>_SU<su_numbers>.ply and edit input.json:

[
  {
    "top": "786",
    "bottom": "787",
    "annotations": ["../lidars/tarpf24477.usdz"]
  }
]
  • "top" / "bottom": job numbers matching PLY filenames
  • "annotations": list of annotation file paths — mode is inferred from extension:
    • .usdz → autosnip (iPhone LiDAR scan with yellow-painted annotation)
    • .png → manual snip (annotated PLY ortho with black stroke outline)

Then run the three scripts in order:

./run.sh pre_snip_script.py input.json
./run.sh auto_snip_script.py input.json
./run.sh post_snip_script.py input.json

Output Files

File Description
Data/<json_id>/*_cleaned_su_<N>.bin Cropped point clouds for each SU
Data/Final_Volumes/SU_<N>_raw.obj Merged Poisson mesh for volume calculation
Data/<top_folder>/SU_<N>_top_raw.obj Top surface mesh
volume_measures.txt Tab-separated: SU name, 3D volume (cm³), 2.5D volume (m³), warnings
Data/<json_id>/debug_topdown_render.png Top-down PLY render used for alignment
Data/<json_id>/debug_SU<N>_{method}_lidar_vs_result.png LiDAR vs PLY comparison per method
Data/<json_id>/debug_SU<N>_manual_annotation.png Ortho with extracted polygon (manual snip)
Data/<json_id>/debug_SU<N>_snip_reference.png Crop region overlay on PLY render

Troubleshooting

CloudComPy import fails ("library load disallowed by system policy"): Re-run the codesign command from the Prerequisites section — the entitlements plist at /tmp/ is ephemeral and may need to be recreated after a reboot.

Autosnip result is in the wrong location: Inspect the debug_SU<N>_{method}_lidar_vs_result.png images for all methods. If none are correct, switch to manual snip: draw the crop boundary in black on debug_topdown_render.png and re-run.

No annotation polygon found in manual snip: Ensure black strokes are truly black (all channels < 50). Increase the morphological close kernel in run_manual_snip() if stroke gaps are large.

"no access right" when opening files in CloudCompare: Use open -a (LaunchServices) rather than calling the binary directly. Copy files with special characters (spaces, commas) to /tmp/ first.

Memory issues during Poisson reconstruction: Reduce depth parameter in post_snip_script.py from 11 to 9 or 10.


API / Vision Methods (Disabled)

Claude Vision (claude-haiku-4-5-20251001) and OpenRouter model methods are preserved in auto_snip_lidar.py as _DISABLED_* functions. To re-enable, remove the _DISABLED_ prefix and set ANTHROPIC_API_KEY or OPEN_ROUTER_KEY in .env.

Evaluation across 4 sites showed gemini-2.5-flash (via OpenRouter) achieves 1.39 m mean centroid error — essentially tied with rgb_pca (1.30 m) but at API cost. See eval_methods.py for the full evaluation framework.


Related Repositories

Repo Purpose
tarp-lab Lab dashboard — Pre-Snip / Auto-Snip / Post-Snip buttons call these scripts directly
su-sheet-builder QGIS script that reads the volume OBJ and writes a georeferenced SU sheet PDF
tarp-field Field website for archaeologists on site

About

Script to automate Cloud Compare processes; part of the Tharros Archaeological Research Project (TARP).

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages