OccPy tutorial notebook for drone-based Laser Scanning (ULS) data¶
This notebook gives a brief overview over ULS occlusion mapping using OccPy.
The data used for this analysis were acquired using a Riegl miniVUX-3 laser scanner mounted on a DJI Matrice M600 pro over the Rameren forest close to the WSL in Birmensdorf, Switzerland. The forest plot is characterized as a mixed temperate forest and the data was acquired under leaf-on conditions. The data has been heavily filtered to reduce storage needs and reduce processing time. The tutorial data is the same as used for the manuscript currently under revision in RSE and available as pre-print here: https://doi.org/10.31223/X5N16X
First, we download the test data and configure paths
import json
import os
import shutil
from pathlib import Path
import pooch
from occpy import OccPy
RIEGL RDBlib is not available RIEGL RiVlib is not available Jupyter environment detected. Enabling Open3D WebVisualizer. [Open3D INFO] WebRTC GUI backend enabled. [Open3D INFO] WebRTCWindowSystem: HTTP handshake server disabled.
# download test data once to cache and mirror it into the repository
repo_root = Path('..', '..').resolve()
data_notebooks = repo_root / 'data_notebooks'
uls_data_dir = data_notebooks / 'ULS_demo'
data_notebooks.mkdir(parents=True, exist_ok=True)
p = pooch.create(
path=pooch.os_cache('occpy_test_data_uls'),
base_url='https://zenodo.org/records/21281997/files/',
registry={'ULS_demo.zip': 'md5:844161a05c1592177ebdf85740d76860'},
)
p.fetch('ULS_demo.zip', processor=pooch.Unzip(members=['ULS_demo']), progressbar=True)
cache_data_dir = Path(p.path) / 'ULS_demo.zip.unzip' / 'ULS_demo'
if not uls_data_dir.exists():
shutil.copytree(cache_data_dir, uls_data_dir)
print(f'Repository notebook data folder: {uls_data_dir}')
config_file = str(repo_root / 'config' / 'settings_ULS_tutorial.JSON')
Repository notebook data folder: /home/wcherlet/occlusion/OccPy/data_notebooks/ULS_demo
OccPy configurations are saved in JSON files.
For mobile acquisitions, it is important to set is_mobile to True.
There are a few minimal requirements for a run:
- laz_in: input laz file or directory containing laz files. If given multiple las files, will assume multi-position TLS. If given single las file, will assume single-position TLS unless is_mobile is set.
- plot_dim: grid for occlusion mapping: [minX, minY, minZ, maxX, maxY, maxZ]
- vox_dim: voxel size - currently this applies to x, y, and z dimension. Non-cubic voxels are on the list of features to be added
Optional arguments:
- is_mobile: whether the acquisition is mobile (MLS/ULS) or static (TLS) (default: False)
- single_return: whether the data is single return or multi return data (default: False)
- out_dir: output directory (default: ./output)
- verbose: set logging level (default: False)
- debug: set logging level (default: False)
- lower_threshold: lower threshold above ground to exclude from occlusion mapping in voxels (default: 0)
- points_per_iter: number of points read in from laz file in each iteration (default: 10000000)
- delimiter: csv delimiter for scan position file (default: ",")
- root_folder: if given, will assume other paths are relative to this root folder and will prepend it to the paths (default: None)
- str_idxs_ScanPosID: string indices of where the scan position identifier is written in the laz file name. If not given, will use file name as ID (without extension) (default: None)
- output_voxels: whether to export .ply voxel grids (large files, slow) (default: False)
Additionally, we use the config file to save paths to other files, such as the positions file, DSM and DTM.
# Load config and resolve all relative paths once for downstream plotting/normalization calls
with open(config_file, 'r') as file:
config = json.load(file)
config
{'root_folder': '../..',
'laz_in': 'data_notebooks/ULS_demo/LAZ/ULS_TestData_20perc_FP10_2025_LeafOn.laz',
'tif_in': {'DTM': 'data_notebooks/ULS_demo/Grids/Ramerenwald_DTM_20250305.tif',
'DSM': 'data_notebooks/ULS_demo/Grids/Ramerenwald_DSM_20250305.tif'},
'out_dir': 'output/ULS',
'vox_dim': 0.1,
'lower_threshold': 1,
'points_per_iter': 1000000,
'plot_dim': [2676515, 1246063, 545, 2676525, 1246113, 590],
'ScanPos': 'data_notebooks/ULS_demo/ScanPos/ULS_TestData_traj_FP10_2025_LeafOn.txt',
'output_voxels': False,
'single_return': False,
'is_mobile': True}
Running OccPy¶
First step is to create an OccPy object with the config file.
test = OccPy(config=config)
INFO: optional arguments: ['out_dir', 'is_mobile', 'output_voxels', 'verbose', 'debug', 'lower_threshold', 'points_per_iter', 'delimiter', 'root_folder', 'single_return', 'str_idxs_ScanPosID', 'cleanup_incomplete_pulses', 'move_senspos_to_collinearity', 'check_returns_all_files']
Then, read in the trajectory information.
test.define_sensor_pos(path2file=config['ScanPos'], # Path to the trajectory file
delimiter=',', # Delimiter used in the trajectory file
hdr_time='Time[s]', # Column header for time
hdr_x='Easting[m]', # Column header for X coordinate
hdr_y='Northing[m]', # Column header for Y coordinate
hdr_z='Height[m]') # Column header for Z coordinate
Now we can start the raytracing and save the outputs.
import time
tic = time.time()
test.do_raytracing()
toc = time.time()
print(f"Raytracing took {toc - tic:.2f} seconds.")
ULS_TestData_20perc_FP10_2025_LeafOn.laz: 100%|██████████| 5.94M/5.94M [00:13<00:00, 448kpts/s] 2026-08-31 11:54:34,324 - WARNING - 9 returns were missed during traversal: they did not fall in a voxel crossed by their own pulse, which means the returns are not collinear with the sensor position. Setting move_senspos_to_collinearity=True can recover them, with the caveats noted in the config documentation.
==================== Occlusion mapping report ==================== Pulses traversed 1,043,716 of 3,393,901 (30.8%) Pulses missing the grid 2,350,185 (69.2%) Returns registered 409,299 Returns outside the grid 634,408 Returns missed 9 Ray tracing time 14.14 s ================================================================== Raytracing took 16.54 seconds.
We can now height normalize the outputs using the provided DTM and DSM file. The DSM file is only to define the upper bounds of the canopy. Function 'normalize_occlusion_output' will also store the normalized voxel grids as npy files in the specified output folder
from occpy.util import normalize_occlusion_output
Nhit_norm, Nmiss_norm, Nocc_norm, Classification_norm, chm = normalize_occlusion_output(input_folder=os.path.join(config["root_folder"], config['out_dir']),
PlotDim=config['plot_dim'],
vox_dim=config['vox_dim'],
dtm_file=os.path.join(config["root_folder"], config['tif_in']['DTM']),
dsm_file=os.path.join(config["root_folder"], config['tif_in']['DSM']),
lower_threshold=config['lower_threshold'],
output_voxels=config['output_voxels'])
# If instead of a binary voxel grid classification, you are intereded in a fraction of occluded pulses per voxel, you can use the following function:
EPS = 1e-6 # small value to avoid division by zero
OcclFrac_norm = Nocc_norm.astype(float) / (Nhit_norm.astype(float) + Nmiss_norm.astype(float) + Nocc_norm.astype(float) + EPS)
Saving normalized output files into directory as .npy...
We can also visualize the results. Note that the amount of occlusion shown here is very high. This is due to the heavy filtering of the input data consisting of only 20% of the original data. The same figure based on the original data can be seen in the paper Kükenbrink et al. (under revision) and available as a pre-print here: https://doi.org/10.31223/X5N16X
from occpy.visualization import plot_transect, plot_profile
# first define figure properties
fig_prop = dict(fig_size=(3.5, 3.2), # figure size in inches
label_size=8, # label size in pts. for e.g. axis labels
label_size_ticks=6, # label size in pts. for e.g. axis ticks
label_size_tiny=5, # label size in pts. for e.g. ticks in colorbar
out_format='png',) # output format of the figure, can be 'png', 'pdf', 'svg', etc.
%matplotlib inline
plot_transect(Nhit_norm, Classification_norm, plot_dim=config['plot_dim'], vox_dim=config['vox_dim'],
out_dir=os.path.join(config["root_folder"], config['out_dir']), axis=0, start_ind=0, end_ind=100, chm=chm, vertBuffer=10, fig_prop=fig_prop, show_plots=True)
# define other figure properties for the smaller figure
fig_prop = dict(fig_size=(1.75, 3.2),
label_size=8,
label_size_ticks=6,
label_size_tiny=5,
out_format='png', )
plot_profile(Classification_norm, plot_dim=config['plot_dim'], vox_dim=config['vox_dim'], out_dir=os.path.join(config["root_folder"], config['out_dir']), low_thresh=0, vertBuffer=10, max_percentage=100, fig_prop=fig_prop, show_plots=True)