anondatasets commited on
Commit
899f359
·
verified ·
1 Parent(s): b298abb

Update point cloud processing code - 2025-09-25T15:11:13.442455

Browse files
point_cloud_preprocessing/00_crop_dem_to_bb.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Crop DEM to match the shared bounding box of the LAS point clouds and convert to ellipsoidal heights.
4
+
5
+ This script:
6
+ 1. Crops a DEM raster to the same spatial extent as the LAS point clouds
7
+ 2. Converts orthometric heights (NAVD88) to ellipsoidal heights (NAD83 2011)
8
+ using the GEOID12B model, ensuring vertical datum compatibility with LAS data
9
+
10
+ Outputs:
11
+ - qspatial_2019_orthometric.tif: Cropped DEM with original orthometric heights
12
+ - qspatial_2019_ellipsoidal.tif: Final DEM with ellipsoidal heights matching LAS data
13
+ """
14
+
15
+ import json
16
+ import subprocess
17
+ from pathlib import Path
18
+ from osgeo import gdal, osr
19
+ import numpy as np
20
+ import tempfile
21
+
22
+ def get_las_bounds(las_file):
23
+ """Get bounding box of LAS file using PDAL info."""
24
+ try:
25
+ result = subprocess.run(
26
+ ['pdal', 'info', '--metadata', str(las_file)],
27
+ capture_output=True,
28
+ text=True,
29
+ check=True
30
+ )
31
+ metadata = json.loads(result.stdout)
32
+
33
+ bounds = {
34
+ 'minx': metadata['metadata']['minx'],
35
+ 'maxx': metadata['metadata']['maxx'],
36
+ 'miny': metadata['metadata']['miny'],
37
+ 'maxy': metadata['metadata']['maxy'],
38
+ 'minz': metadata['metadata']['minz'],
39
+ 'maxz': metadata['metadata']['maxz']
40
+ }
41
+
42
+ # Also get the SRS info
43
+ srs_wkt = metadata['metadata']['spatialreference']
44
+
45
+ return bounds, srs_wkt
46
+ except subprocess.CalledProcessError as e:
47
+ raise RuntimeError(f"Failed to get bounds for {las_file}: {e}")
48
+
49
+ def calculate_shared_bounds(las_files):
50
+ """Calculate the smallest shared bounding box from multiple LAS files."""
51
+ bounds_list = []
52
+ srs_wkt = None
53
+
54
+ for las_file in las_files:
55
+ bounds, wkt = get_las_bounds(las_file)
56
+ bounds_list.append(bounds)
57
+ if srs_wkt is None:
58
+ srs_wkt = wkt
59
+
60
+ shared_bounds = {
61
+ 'minx': max(b['minx'] for b in bounds_list),
62
+ 'maxx': min(b['maxx'] for b in bounds_list),
63
+ 'miny': max(b['miny'] for b in bounds_list),
64
+ 'maxy': min(b['maxy'] for b in bounds_list),
65
+ }
66
+
67
+ # Validate that we have a valid bounding box
68
+ if (shared_bounds['minx'] >= shared_bounds['maxx'] or
69
+ shared_bounds['miny'] >= shared_bounds['maxy']):
70
+ raise ValueError("No spatial overlap between input files")
71
+
72
+ return shared_bounds, srs_wkt
73
+
74
+ def crop_dem_to_bounds(input_dem, output_dem, bounds, target_srs_wkt=None):
75
+ """
76
+ Crop DEM to specified bounds using GDAL.
77
+
78
+ Args:
79
+ input_dem: Path to input DEM file
80
+ output_dem: Path to output cropped DEM
81
+ bounds: Dictionary with minx, maxx, miny, maxy
82
+ target_srs_wkt: Target SRS in WKT format (optional, for reprojection)
83
+ """
84
+ # Open the input DEM
85
+ src_ds = gdal.Open(str(input_dem))
86
+ if src_ds is None:
87
+ raise RuntimeError(f"Failed to open {input_dem}")
88
+
89
+ # Get source SRS
90
+ src_srs = osr.SpatialReference()
91
+ src_srs.ImportFromWkt(src_ds.GetProjection())
92
+
93
+ # Set up target SRS if provided
94
+ if target_srs_wkt:
95
+ target_srs = osr.SpatialReference()
96
+ target_srs.ImportFromWkt(target_srs_wkt)
97
+
98
+ # Check if reprojection is needed
99
+ if not src_srs.IsSame(target_srs):
100
+ print(" Note: DEM and LAS use different coordinate systems")
101
+ print(f" DEM SRS: {src_srs.GetAttrValue('PROJCS') or src_srs.GetAttrValue('GEOGCS')}")
102
+ print(f" LAS SRS: {target_srs.GetAttrValue('PROJCS') or target_srs.GetAttrValue('GEOGCS')}")
103
+
104
+ # Use GDAL Warp to crop (and optionally reproject)
105
+ warp_options = gdal.WarpOptions(
106
+ outputBounds=[bounds['minx'], bounds['miny'], bounds['maxx'], bounds['maxy']],
107
+ outputBoundsSRS=target_srs_wkt if target_srs_wkt else None,
108
+ dstSRS=target_srs_wkt if target_srs_wkt else None,
109
+ resampleAlg='bilinear',
110
+ format='GTiff',
111
+ creationOptions=['COMPRESS=LZW', 'TILED=YES']
112
+ )
113
+
114
+ # Perform the warp operation
115
+ gdal.Warp(str(output_dem), src_ds, options=warp_options)
116
+
117
+ # Close dataset
118
+ src_ds = None
119
+
120
+ # Verify output
121
+ result_ds = gdal.Open(str(output_dem))
122
+ if result_ds is None:
123
+ raise RuntimeError(f"Failed to create {output_dem}")
124
+
125
+ # Get output info
126
+ geotransform = result_ds.GetGeoTransform()
127
+ width = result_ds.RasterXSize
128
+ height = result_ds.RasterYSize
129
+
130
+ # Calculate actual bounds of output
131
+ actual_minx = geotransform[0]
132
+ actual_maxy = geotransform[3]
133
+ actual_maxx = actual_minx + width * geotransform[1]
134
+ actual_miny = actual_maxy + height * geotransform[5]
135
+
136
+ # Get elevation statistics
137
+ band = result_ds.GetRasterBand(1)
138
+ stats = band.GetStatistics(True, True)
139
+ min_elev, max_elev, mean_elev, std_elev = stats
140
+
141
+ result_ds = None
142
+
143
+ return {
144
+ 'width': width,
145
+ 'height': height,
146
+ 'pixel_size': abs(geotransform[1]),
147
+ 'bounds': {
148
+ 'minx': actual_minx,
149
+ 'maxx': actual_maxx,
150
+ 'miny': actual_miny,
151
+ 'maxy': actual_maxy
152
+ },
153
+ 'elevation': {
154
+ 'min': min_elev,
155
+ 'max': max_elev,
156
+ 'mean': mean_elev,
157
+ 'std': std_elev
158
+ }
159
+ }
160
+
161
+ def convert_to_ellipsoidal_height(input_dem, output_dem, geoid_file):
162
+ """
163
+ Convert orthometric heights to ellipsoidal heights using GDAL warp + raster math.
164
+
165
+ This approach:
166
+ 1. Warps the geoid to match the DEM's projection and resolution
167
+ 2. Adds the geoid separation to the orthometric heights: ellipsoidal = orthometric + geoid
168
+
169
+ Args:
170
+ input_dem: Path to input DEM with orthometric heights
171
+ output_dem: Path to output DEM with ellipsoidal heights
172
+ geoid_file: Path to geoid model file (GEOID12B binary format)
173
+ """
174
+ print(f" Warping geoid to match DEM projection and resolution...")
175
+
176
+ # Open the DEM to get its spatial reference and geotransform
177
+ dem_ds = gdal.Open(str(input_dem))
178
+ if dem_ds is None:
179
+ raise RuntimeError(f"Failed to open {input_dem}")
180
+
181
+ dem_proj = dem_ds.GetProjection()
182
+ dem_geotransform = dem_ds.GetGeoTransform()
183
+ dem_width = dem_ds.RasterXSize
184
+ dem_height = dem_ds.RasterYSize
185
+
186
+ # Calculate DEM bounds
187
+ minx = dem_geotransform[0]
188
+ maxy = dem_geotransform[3]
189
+ maxx = minx + dem_width * dem_geotransform[1]
190
+ miny = maxy + dem_height * dem_geotransform[5]
191
+
192
+ # Create temporary warped geoid file
193
+ temp_geoid = tempfile.NamedTemporaryFile(suffix='_warped_geoid.tif', delete=False)
194
+ temp_geoid_path = temp_geoid.name
195
+ temp_geoid.close()
196
+
197
+ try:
198
+ # Warp geoid to match DEM
199
+ warp_options = gdal.WarpOptions(
200
+ format='GTiff',
201
+ outputBounds=[minx, miny, maxx, maxy],
202
+ width=dem_width,
203
+ height=dem_height,
204
+ dstSRS=dem_proj,
205
+ resampleAlg='bilinear',
206
+ creationOptions=['COMPRESS=LZW', 'TILED=YES']
207
+ )
208
+
209
+ print(f" Warping {geoid_file} to match DEM...")
210
+ gdal.Warp(temp_geoid_path, str(geoid_file), options=warp_options)
211
+
212
+ # Verify warped geoid was created
213
+ geoid_ds = gdal.Open(temp_geoid_path)
214
+ if geoid_ds is None:
215
+ raise RuntimeError(f"Failed to warp geoid file")
216
+
217
+ print(f" Adding geoid separation to orthometric heights...")
218
+
219
+ # Read the DEM data
220
+ dem_band = dem_ds.GetRasterBand(1)
221
+ dem_data = dem_band.ReadAsArray()
222
+ dem_nodata = dem_band.GetNoDataValue()
223
+
224
+ # Read the warped geoid data
225
+ geoid_band = geoid_ds.GetRasterBand(1)
226
+ geoid_data = geoid_band.ReadAsArray()
227
+
228
+ # Ensure arrays have the same shape
229
+ if dem_data.shape != geoid_data.shape:
230
+ raise RuntimeError(f"DEM and geoid array shapes don't match: {dem_data.shape} vs {geoid_data.shape}")
231
+
232
+ # Apply conversion: ellipsoidal = orthometric + geoid
233
+ ellipsoidal_data = dem_data.copy()
234
+
235
+ if dem_nodata is not None:
236
+ # Only apply to valid pixels
237
+ valid_mask = dem_data != dem_nodata
238
+ ellipsoidal_data[valid_mask] = dem_data[valid_mask] + geoid_data[valid_mask]
239
+ else:
240
+ # Apply to all pixels
241
+ ellipsoidal_data = dem_data + geoid_data
242
+
243
+ # Create output DEM
244
+ driver = gdal.GetDriverByName('GTiff')
245
+ out_ds = driver.Create(
246
+ str(output_dem),
247
+ dem_width,
248
+ dem_height,
249
+ 1,
250
+ gdal.GDT_Float32,
251
+ ['COMPRESS=LZW', 'TILED=YES']
252
+ )
253
+
254
+ # Set spatial reference and geotransform
255
+ out_ds.SetProjection(dem_proj)
256
+ out_ds.SetGeoTransform(dem_geotransform)
257
+
258
+ # Write the ellipsoidal data
259
+ out_band = out_ds.GetRasterBand(1)
260
+ out_band.WriteArray(ellipsoidal_data)
261
+ if dem_nodata is not None:
262
+ out_band.SetNoDataValue(dem_nodata)
263
+
264
+ # Get statistics
265
+ stats = out_band.GetStatistics(True, True)
266
+ min_elev, max_elev, mean_elev, std_elev = stats
267
+
268
+ # Calculate average geoid separation (for reporting)
269
+ if dem_nodata is not None:
270
+ valid_geoid = geoid_data[valid_mask]
271
+ avg_geoid_sep = np.mean(valid_geoid) if len(valid_geoid) > 0 else 0
272
+ else:
273
+ avg_geoid_sep = np.mean(geoid_data)
274
+
275
+ # Close datasets
276
+ dem_ds = None
277
+ geoid_ds = None
278
+ out_ds = None
279
+
280
+ return {
281
+ 'elevation': {
282
+ 'min': min_elev,
283
+ 'max': max_elev,
284
+ 'mean': mean_elev,
285
+ 'std': std_elev
286
+ },
287
+ 'avg_geoid_separation': avg_geoid_sep,
288
+ 'method': 'gdal_warp_plus_raster_math'
289
+ }
290
+
291
+ finally:
292
+ # Clean up temporary file
293
+ try:
294
+ Path(temp_geoid_path).unlink()
295
+ except:
296
+ pass # Ignore cleanup errors
297
+
298
+ def main():
299
+ # Input paths
300
+ input_dem = Path('/Users/kdoherty/bitterroot_canopy/data/raster/lidar_raw/dems/2019/46114f1_2019_qspatial_dem.tif')
301
+ geoid_file = Path('data/raster/dems/g2012bu1.bin')
302
+ las_dir = Path('data/point_cloud')
303
+
304
+ # LAS files to get bounds from (three timepoints)
305
+ las_files = [
306
+ las_dir / '1000.las',
307
+ las_dir / '1200.las',
308
+ las_dir / '1500.las'
309
+ ]
310
+
311
+ # Output paths
312
+ output_dir = Path('data/raster/dems')
313
+ output_dir.mkdir(parents=True, exist_ok=True)
314
+
315
+ # Intermediate file (orthometric heights, cropped)
316
+ orthometric_dem = output_dir / 'qspatial_2019_orthometric.tif'
317
+ # Final file (ellipsoidal heights)
318
+ ellipsoidal_dem = output_dir / 'qspatial_2019_ellipsoidal.tif'
319
+
320
+ # Validate input files exist
321
+ if not input_dem.exists():
322
+ raise FileNotFoundError(f"Input DEM not found: {input_dem}")
323
+
324
+ if not geoid_file.exists():
325
+ raise FileNotFoundError(f"Geoid file not found: {geoid_file}")
326
+
327
+ for las_file in las_files:
328
+ if not las_file.exists():
329
+ raise FileNotFoundError(f"LAS file not found: {las_file}")
330
+
331
+ print("Analyzing three timepoint LAS files for shared bounding box...")
332
+
333
+ # Get shared bounds from LAS files
334
+ shared_bounds, las_srs_wkt = calculate_shared_bounds(las_files)
335
+
336
+ print(f"\nShared bounding box across timepoints:")
337
+ print(f" X: {shared_bounds['minx']:.3f} → {shared_bounds['maxx']:.3f}")
338
+ print(f" Y: {shared_bounds['miny']:.3f} → {shared_bounds['maxy']:.3f}")
339
+ print(f" Width: {shared_bounds['maxx'] - shared_bounds['minx']:.3f} m")
340
+ print(f" Height: {shared_bounds['maxy'] - shared_bounds['miny']:.3f} m")
341
+
342
+ print(f"\nStep 1: Cropping DEM to LAS bounds...")
343
+ print(f" Input: {input_dem}")
344
+ print(f" Output: {orthometric_dem}")
345
+
346
+ # Crop the DEM (orthometric heights)
347
+ crop_result = crop_dem_to_bounds(input_dem, orthometric_dem, shared_bounds, las_srs_wkt)
348
+
349
+ print(f"\nCrop complete!")
350
+ print(f" Output dimensions: {crop_result['width']} x {crop_result['height']} pixels")
351
+ print(f" Pixel size: {crop_result['pixel_size']:.3f} m")
352
+ print(f" Final bounds:")
353
+ print(f" X: {crop_result['bounds']['minx']:.3f} → {crop_result['bounds']['maxx']:.3f}")
354
+ print(f" Y: {crop_result['bounds']['miny']:.3f} → {crop_result['bounds']['maxy']:.3f}")
355
+ print(f" Orthometric elevation range:")
356
+ print(f" Min: {crop_result['elevation']['min']:.2f} m")
357
+ print(f" Max: {crop_result['elevation']['max']:.2f} m")
358
+ print(f" Mean: {crop_result['elevation']['mean']:.2f} m (±{crop_result['elevation']['std']:.2f})")
359
+
360
+ print(f"\nStep 2: Converting to ellipsoidal heights...")
361
+ print(f" Input: {orthometric_dem}")
362
+ print(f" Geoid: {geoid_file}")
363
+ print(f" Output: {ellipsoidal_dem}")
364
+
365
+ # Convert orthometric heights to ellipsoidal heights
366
+ conversion_result = convert_to_ellipsoidal_height(orthometric_dem, ellipsoidal_dem, geoid_file)
367
+
368
+ print(f"\nConversion complete!")
369
+ print(f" Ellipsoidal elevation range:")
370
+ print(f" Min: {conversion_result['elevation']['min']:.2f} m")
371
+ print(f" Max: {conversion_result['elevation']['max']:.2f} m")
372
+ print(f" Mean: {conversion_result['elevation']['mean']:.2f} m (±{conversion_result['elevation']['std']:.2f})")
373
+
374
+ # Show conversion method used
375
+ if 'method' in conversion_result:
376
+ print(f" Conversion method: {conversion_result['method']}")
377
+
378
+ # Show geoid separation statistics
379
+ if 'avg_geoid_separation' in conversion_result:
380
+ print(f" Average geoid separation: {conversion_result['avg_geoid_separation']:.3f} m")
381
+ else:
382
+ # Fallback calculation
383
+ ortho_mean = crop_result['elevation']['mean']
384
+ ellip_mean = conversion_result['elevation']['mean']
385
+ geoid_sep = ellip_mean - ortho_mean
386
+ print(f" Average geoid separation: {geoid_sep:.3f} m")
387
+
388
+ if __name__ == "__main__":
389
+ main()
point_cloud_preprocessing/01_normalize_and_chm.R ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Load required libraries
2
+ library(lidR)
3
+ library(raster)
4
+ library(terra)
5
+ library(sf)
6
+ library(jsonlite)
7
+
8
+ # Ground classification function using DEM (for catalog chunks)
9
+ classify_ground_by_dem <- function(las, dem_raster, tol) {
10
+
11
+ # Convert raster to terra SpatRaster if needed
12
+ if (class(dem_raster)[1] == "RasterLayer") {
13
+ dem <- terra::rast(dem_raster)
14
+ } else {
15
+ dem <- dem_raster
16
+ }
17
+
18
+ # Create points for extraction
19
+ points_df <- data.frame(
20
+ X = las@data$X,
21
+ Y = las@data$Y,
22
+ Z = las@data$Z
23
+ )
24
+
25
+ # Create SpatVector from points
26
+ pts <- terra::vect(points_df[, c("X", "Y")],
27
+ geom = c("X", "Y"),
28
+ crs = terra::crs(dem))
29
+
30
+ # Extract DEM values at point locations
31
+ dem_values <- terra::extract(dem, pts, ID = FALSE)
32
+ dem_col_name <- names(dem_values)[1]
33
+
34
+ # Check for NA values
35
+ na_count <- sum(is.na(dem_values[[dem_col_name]]))
36
+
37
+ # Calculate vertical distances for valid points
38
+ valid_idx <- which(!is.na(dem_values[[dem_col_name]]))
39
+ z_diff <- abs(points_df$Z[valid_idx] - dem_values[[dem_col_name]][valid_idx])
40
+
41
+ # Initialize classification (1 = unclassified)
42
+ classification <- rep(1, nrow(points_df))
43
+
44
+ # Classify ground points (within tolerance)
45
+ ground_indices <- valid_idx[z_diff <= tol]
46
+ classification[ground_indices] <- 2 # ASPRS ground class
47
+
48
+ # Classify vegetation points (beyond tolerance)
49
+ veg_indices <- valid_idx[z_diff > tol]
50
+ classification[veg_indices] <- 5 # ASPRS vegetation class
51
+
52
+ # Update LAS classification (ensure integer type)
53
+ las@data$Classification <- as.integer(classification)
54
+
55
+ return(las)
56
+ }
57
+
58
+ # Load metadata for z-error threshold calculation
59
+ metadata <- fromJSON("data/point_cloud/metadata.json")
60
+ z_errors <- sapply(metadata$acquisitions, function(x) x$z_error)
61
+ mean_z_error <- mean(z_errors)
62
+ cat(sprintf("Ground threshold: %.3f m (mean z-error)\n", mean_z_error))
63
+
64
+ # File paths for three timepoints
65
+ las_files <- c(
66
+ "data/point_cloud/1000.las",
67
+ "data/point_cloud/1200.las",
68
+ "data/point_cloud/1500.las"
69
+ )
70
+ ellipsoidal_dem <- "data/raster/dems/qspatial_2019_ellipsoidal.tif"
71
+ output_chm <- "data/raster/dems/canopy_height.tif"
72
+ target_resolution <- 0.05 # meters
73
+
74
+ # Validate input files
75
+ for (las_file in las_files) {
76
+ if (!file.exists(las_file)) {
77
+ stop(paste("Required file not found:", las_file))
78
+ }
79
+ }
80
+ if (!file.exists(ellipsoidal_dem)) {
81
+ stop(paste("Required file not found:", ellipsoidal_dem))
82
+ }
83
+
84
+ # Function to calculate shared bounding box
85
+ get_shared_bounds <- function(las_files) {
86
+ cat("\nStep 1: Calculating shared bounding box...\n")
87
+
88
+ bounds_list <- list()
89
+ for (i in 1:length(las_files)) {
90
+ las <- readLAS(las_files[i], select = "xyz") # Only read coordinates for speed
91
+ bounds_list[[i]] <- list(
92
+ xmin = min(las@data$X),
93
+ xmax = max(las@data$X),
94
+ ymin = min(las@data$Y),
95
+ ymax = max(las@data$Y)
96
+ )
97
+ cat(sprintf(" %s: X(%.2f,%.2f) Y(%.2f,%.2f)\n",
98
+ basename(las_files[i]),
99
+ bounds_list[[i]]$xmin, bounds_list[[i]]$xmax,
100
+ bounds_list[[i]]$ymin, bounds_list[[i]]$ymax))
101
+ }
102
+
103
+ # Calculate intersection (minimum bounding box)
104
+ shared_bounds <- list(
105
+ xmin = max(sapply(bounds_list, function(b) b$xmin)),
106
+ xmax = min(sapply(bounds_list, function(b) b$xmax)),
107
+ ymin = max(sapply(bounds_list, function(b) b$ymin)),
108
+ ymax = min(sapply(bounds_list, function(b) b$ymax))
109
+ )
110
+
111
+ cat(sprintf(" Shared bounds: X(%.2f,%.2f) Y(%.2f,%.2f)\n",
112
+ shared_bounds$xmin, shared_bounds$xmax,
113
+ shared_bounds$ymin, shared_bounds$ymax))
114
+ cat(sprintf(" Shared area: %.1f x %.1f m\n",
115
+ shared_bounds$xmax - shared_bounds$xmin,
116
+ shared_bounds$ymax - shared_bounds$ymin))
117
+
118
+ return(shared_bounds)
119
+ }
120
+
121
+ # Calculate shared bounding box
122
+ shared_bounds <- get_shared_bounds(las_files)
123
+
124
+ # Create template raster for consistent CRS and extent
125
+ las_crs <- sf::st_crs(readLAS(las_files[1], select = "xyz"))$wkt
126
+ template_raster <- terra::rast(xmin = shared_bounds$xmin,
127
+ xmax = shared_bounds$xmax,
128
+ ymin = shared_bounds$ymin,
129
+ ymax = shared_bounds$ymax,
130
+ res = target_resolution,
131
+ crs = las_crs)
132
+
133
+ cat(sprintf(" Template raster: %d x %d pixels, CRS: %s\n",
134
+ ncol(template_raster), nrow(template_raster),
135
+ substr(las_crs, 1, 50)))
136
+
137
+ cat("\nStep 2: Loading ellipsoidal DEM...\n")
138
+ cat(sprintf(" Input: %s\n", ellipsoidal_dem))
139
+ dtm <- raster(ellipsoidal_dem)
140
+ cat(sprintf(" DEM dimensions: %d x %d pixels\n", ncol(dtm), nrow(dtm)))
141
+ cat(sprintf(" DEM resolution: %.3f m\n", res(dtm)[1]))
142
+ cat(sprintf(" DEM elevation range: %.2f to %.2f meters\n", cellStats(dtm, min), cellStats(dtm, max)))
143
+
144
+
145
+ # Function to process a single timepoint
146
+ process_timepoint <- function(las_file, template, dtm, mean_z_error) {
147
+ timepoint <- tools::file_path_sans_ext(basename(las_file))
148
+ cat(sprintf("\n Processing timepoint %s...\n", timepoint))
149
+
150
+ # Read LAS file
151
+ las <- readLAS(las_file)
152
+ cat(sprintf(" Loaded %s points\n", format(npoints(las), big.mark = ",")))
153
+
154
+ # Fix return metadata for photogrammetric point cloud
155
+ las@data$ReturnNumber <- as.integer(1)
156
+ las@data$NumberOfReturns <- as.integer(1)
157
+
158
+ # Classify ground points
159
+ cat(" Classifying ground points using DEM...\n")
160
+ las <- classify_ground_by_dem(las, dtm, mean_z_error)
161
+
162
+ # Normalize heights using TIN from classified ground points
163
+ cat(" Normalizing heights using TIN...\n")
164
+ las_norm <- normalize_height(las, algorithm = tin())
165
+
166
+ # Clamp negative values to 0
167
+ las_norm@data$Z[las_norm@data$Z < 0] <- 0.0
168
+
169
+ # --- THIS IS THE CRUCIAL FIX ---
170
+ # Clip the point cloud to the template's extent before rasterizing.
171
+ # This prevents the "point out of raster" error.
172
+ cat(" Clipping point cloud to shared extent...\n")
173
+ bbox <- raster::extent(template)
174
+ las_clipped <- clip_rectangle(las_norm, bbox@xmin, bbox@ymin, bbox@xmax, bbox@ymax)
175
+
176
+ # Check if any points remain after clipping
177
+ if (is.empty(las_clipped)) {
178
+ cat(" Warning: No points remaining after clipping. Skipping this timepoint.\n")
179
+ return(NULL)
180
+ }
181
+
182
+ # Generate CHM using the clipped point cloud and the pitfree algorithm
183
+ cat(sprintf(" Generating CHM using template grid (%.3f m resolution)...\n", xres(template)))
184
+ chm <- rasterize_canopy(
185
+ las_clipped, # <-- Use the clipped LAS object
186
+ res = template, # Use the template raster directly
187
+ algorithm = p2r(subcircle = 0.5 * xres(template), na.fill = knnidw())
188
+ )
189
+
190
+ # Clamp negative values that may be introduced by interpolation
191
+ chm[chm < 0] <- 0
192
+
193
+ # Apply Gaussian smoothing to reduce noise
194
+ cat(" Applying Gaussian smoothing...\n")
195
+ chm_terra <- terra::rast(chm)
196
+ chm_smoothed <- terra::focal(chm_terra, w=3, fun="mean", na.rm=TRUE)
197
+ chm <- raster(chm_smoothed) # Convert back to raster for consistency
198
+
199
+ # Verify we have data
200
+ max_val <- cellStats(chm, "max")
201
+ if (is.na(max_val) || max_val == -Inf || max_val <= 0) {
202
+ cat(" Warning: CHM has no positive values after generation.\n")
203
+ return(NULL)
204
+ }
205
+
206
+ # Convert final raster to SpatRaster for consistency before returning
207
+ chm_terra <- terra::rast(chm)
208
+
209
+ cat(sprintf(" CHM: %d x %d pixels, Height range: %.2f to %.2f m\n",
210
+ ncol(chm_terra), nrow(chm_terra),
211
+ terra::global(chm_terra, "min", na.rm = TRUE)[1,1],
212
+ terra::global(chm_terra, "max", na.rm = TRUE)[1,1]))
213
+
214
+ return(chm_terra)
215
+ }
216
+
217
+ cat("\nStep 3: Processing each timepoint...\n")
218
+
219
+ # --- ADDED: Convert terra template to raster for lidR compatibility ---
220
+ # lidR's rasterize_* functions expect a RasterLayer object from the 'raster' package
221
+ template_raster_legacy <- raster(template_raster)
222
+
223
+ # Check if CHM already exists
224
+ if (file.exists(output_chm)) {
225
+ cat(sprintf(" CHM already exists, skipping: %s\n", output_chm))
226
+ chm <- terra::rast(output_chm)
227
+ cat(sprintf(" Loaded existing CHM: %d x %d pixels\n", ncol(chm), nrow(chm)))
228
+ cat(sprintf(" CHM height range: %.2f to %.2f meters\n",
229
+ terra::global(chm, "min", na.rm = TRUE)[1,1],
230
+ terra::global(chm, "max", na.rm = TRUE)[1,1]))
231
+ } else {
232
+ # Process each timepoint to generate CHMs
233
+ chm_list <- list()
234
+
235
+ for (i in 1:length(las_files)) {
236
+ chm_result <- process_timepoint(las_files[i], template_raster_legacy, dtm, mean_z_error)
237
+ if (!is.null(chm_result)) {
238
+ chm_list[[length(chm_list) + 1]] <- chm_result
239
+ }
240
+ }
241
+
242
+ cat(sprintf("\nStep 4: Averaging %d CHMs across timepoints...\n", length(chm_list)))
243
+
244
+ if (length(chm_list) == 0) {
245
+ stop("No valid CHMs were generated from any timepoint!")
246
+ }
247
+
248
+ # Average the CHMs
249
+ if (length(chm_list) == 1) {
250
+ final_chm <- chm_list[[1]]
251
+ cat(" Using single CHM (only one timepoint processed successfully)\n")
252
+ } else {
253
+ chm_stack <- terra::rast(chm_list)
254
+ final_chm <- terra::app(chm_stack, mean, na.rm = TRUE)
255
+ }
256
+
257
+ cat(sprintf(" Final CHM: %d x %d pixels, Height range: %.2f to %.2f m\n",
258
+ ncol(final_chm), nrow(final_chm),
259
+ terra::global(final_chm, "min", na.rm = TRUE)[1,1],
260
+ terra::global(final_chm, "max", na.rm = TRUE)[1,1]))
261
+
262
+ cat(sprintf(" Saving averaged CHM: %s\n", output_chm))
263
+ dir.create(dirname(output_chm), showWarnings = FALSE, recursive = TRUE)
264
+ terra::writeRaster(final_chm, output_chm, overwrite = TRUE)
265
+ }
266
+
267
+ cat(sprintf("\nProcessing complete!\n"))
268
+ cat(sprintf(" Averaged CHM (%.3f m): %s\n", target_resolution, output_chm))
269
+ cat(sprintf(" Based on %d timepoints: %s\n", length(las_files),
270
+ paste(basename(tools::file_path_sans_ext(las_files)), collapse = ", ")))