City3D-MultiGen / scripts /melbourne /export_las_blocks_noKML.py
e32's picture
Initial release: reconstruction pipeline + metadata
e95f494 verified
Raw
History Blame Contribute Delete
38.9 kB
"""
Melbourne LAS tiler for the City3D-MultiGen reconstruction pipeline.
Role in pipeline:
This script partitions Melbourne's source airborne LiDAR (distributed as LAS/LAZ)
into regular ground-plane tiles and produces the per-tile point cloud, DSM, and BEV
products consumed by the downstream City3D-MultiGen dataset (the GridFlow training
corpus). It is the Melbourne counterpart of the per-city tilers.
Inputs:
- One or more source LAS/LAZ files in TILE_DIR (auto-scanned when INPUT_LAS_FILES
is None, otherwise the explicitly listed files). The CRS is read from the LAS
headers (falling back to UTM auto-detection from coordinates).
Processing steps:
1. Read each input file's XY extent and build one WGS84 polygon per file.
2. Generate a regular grid of GRID_SIZE (150 m) tiles, keeping only tiles whose
center falls inside an input polygon; spacing yields overlapping tiles.
3. Emit a KML visualization of the grid.
4. Scan all tiles for bounds and (optionally) a global elevation range so DSMs
share a consistent vertical scale.
5. For each grid tile: crop the overlapping source files to the tile bounds,
optionally voxel-downsample, then rasterize a BEV PNG and a DSM (GeoTIFF + PNG),
writing a per-tile JSON log. RESUME_MODE skips tiles already fully produced.
Outputs (per tile, named grid_<id>):
- grid_<id>.las/.laz : cropped point cloud for the tile
- grid_<id>_bev.png : top-down BEV render (RGB, optional transparency)
- grid_<id>_dsm.tif/png: digital surface model raster (georeferenced + 16-bit PNG)
- grid_<id>.json : per-tile metadata (bounds, point count, elevations)
Plus output_grids.kml and processing_summary.json at the dataset level.
External tools:
- PDAL (invoked via subprocess as `pdal pipeline`) for cropping/voxel filtering.
- GDAL/OSR for writing georeferenced DSM GeoTIFFs.
- laspy, numpy, Pillow, scipy, pyproj for I/O and rasterization.
"""
import json
import os
import subprocess
import tempfile
from pathlib import Path
from pyproj import Transformer
from typing import List, Tuple, Dict
import laspy
import numpy as np
from PIL import Image
from tqdm import tqdm
from scipy.ndimage import uniform_filter
GRID_SIZE = 150
GRID_SPACING = -130 # 150 m tile - 130 m overlap = 20 m center spacing (paper setting)
INPUT_LAS_FILES = None
TILE_DIR = "./LAS"
OUTPUT_DIR = "./output"
VOXEL_SIZE = 0.05
TEST_MODE_LIMIT = None
DEBUG_MODE = False
USE_VOXEL_FILTER = False
PYTHON_VOXEL_DEDUP = False
OUTPUT_COMPRESSED = False
RESUME_MODE = True
FORCE_REPROCESS = False
BEV_POINT_SIZE = 8
BEV_TRANSPARENT_BG = True
BEV_USE_RGB = True
BEV_POINT_OPACITY = 1.0
BEV_OPACITY_MODE = "fixed"
BEV_ADAPTIVE_POINT_SIZE = True
BEV_POINT_SIZE_MIN = 3
BEV_POINT_SIZE_MAX = 3
BEV_DENSITY_WINDOW = 10
MEMORY_OPTIMIZATION = True
BEV_RESOLUTION = 256
MAX_POINTS_IN_MEMORY = 10000000
GENERATE_DSM = True
DSM_RESOLUTION = 256
DSM_POINT_SIZE = 3
DSM_USE_GLOBAL_RANGE = True
def parse_las_boundaries(las_files: List[str], tile_dir: str) -> Tuple[List[List[Tuple[float, float]]], str]:
if las_files is None or len(las_files) == 0:
print(f"AUTO-SCAN MODE: Scanning all LAS files in {tile_dir}")
las_paths = list(Path(tile_dir).glob("*.las")) + list(Path(tile_dir).glob("*.laz"))
las_paths = [f for f in las_paths if not f.name.startswith("grid_")]
las_files = [f.name for f in las_paths]
if len(las_files) == 0:
raise ValueError(f"No LAS files found in {tile_dir}")
print(f"Found {len(las_files)} LAS files:")
for f in las_files:
print(f" - {f}")
else:
print(f"MANUAL MODE: Using {len(las_files)} specified files")
print(f"\nReading boundaries from {len(las_files)} LAS files")
print("Creating individual polygons for each input file to preserve neighboring relationships")
all_bounds = []
crs_list = []
for las_file in las_files:
las_path = os.path.join(tile_dir, las_file)
if not os.path.exists(las_path):
print(f"Warning: File not found: {las_path}")
continue
try:
with laspy.open(las_path) as f:
header = f.header
bounds = {
'file': las_file,
'min_x': header.x_min,
'max_x': header.x_max,
'min_y': header.y_min,
'max_y': header.y_max
}
all_bounds.append(bounds)
if hasattr(header, 'parse_crs'):
crs = header.parse_crs()
if crs:
crs_list.append(str(crs))
print(f" {las_file}: X=[{bounds['min_x']:.2f}, {bounds['max_x']:.2f}], Y=[{bounds['min_y']:.2f}, {bounds['max_y']:.2f}]")
except Exception as e:
print(f"Error reading {las_file}: {e}")
continue
if not all_bounds:
raise ValueError("No valid LAS files found")
overall_min_x = min(b['min_x'] for b in all_bounds)
overall_max_x = max(b['max_x'] for b in all_bounds)
overall_min_y = min(b['min_y'] for b in all_bounds)
overall_max_y = max(b['max_y'] for b in all_bounds)
print(f"\nOverall boundary: X=[{overall_min_x:.2f}, {overall_max_x:.2f}], Y=[{overall_min_y:.2f}, {overall_max_y:.2f}]")
if crs_list:
detected_crs = crs_list[0]
print(f"Detected CRS: {detected_crs}")
if 'EPSG:' in detected_crs:
utm_crs = detected_crs.split('EPSG:')[1].split()[0]
utm_crs = f"EPSG:{utm_crs}"
else:
print("Warning: Could not parse EPSG code, using auto-detection")
center_x = (overall_min_x + overall_max_x) / 2
center_y = (overall_min_y + overall_max_y) / 2
utm_crs = auto_detect_utm_from_coords(center_x, center_y)
else:
print("Warning: No CRS found in LAS headers, using auto-detection")
center_x = (overall_min_x + overall_max_x) / 2
center_y = (overall_min_y + overall_max_y) / 2
utm_crs = auto_detect_utm_from_coords(center_x, center_y)
print(f"Using UTM CRS: {utm_crs}")
transformer_to_wgs = Transformer.from_crs(utm_crs, "EPSG:4326", always_xy=True)
polygons_wgs84 = []
for i, bounds in enumerate(all_bounds):
rectangle_utm = [
(bounds['min_x'], bounds['max_y']),
(bounds['max_x'], bounds['max_y']),
(bounds['max_x'], bounds['min_y']),
(bounds['min_x'], bounds['min_y'])
]
rectangle_wgs84 = []
for x, y in rectangle_utm:
lon, lat = transformer_to_wgs.transform(x, y)
rectangle_wgs84.append((lon, lat))
polygons_wgs84.append(rectangle_wgs84)
print(f" Created polygon {i+1} for {bounds['file']}")
print(f"\nCreated {len(polygons_wgs84)} individual polygons (one per input file)")
print("Grids will only be generated where they overlap with these polygons")
return polygons_wgs84, utm_crs
def auto_detect_utm_from_coords(x: float, y: float) -> str:
if 100000 < x < 900000 and 1000000 < y < 10000000:
if y > 5000000:
zone = int((x + 500000) / 1000000) + 30
return f"EPSG:326{zone:02d}"
else:
zone = int((x + 500000) / 1000000) + 30
return f"EPSG:327{zone:02d}"
else:
print(f"Warning: Coordinates ({x}, {y}) do not match typical UTM range")
return "EPSG:32650"
def get_utm_zone(lon: float, lat: float) -> str:
zone = int((lon + 180) / 6) + 1
hemisphere = 'north' if lat >= 0 else 'south'
return f"EPSG:326{zone:02d}" if hemisphere == 'north' else f"EPSG:327{zone:02d}"
def point_in_polygon(point: Tuple[float, float], polygon: List[Tuple[float, float]]) -> bool:
x, y = point
n = len(polygon)
inside = False
p1x, p1y = polygon[0]
for i in range(1, n + 1):
p2x, p2y = polygon[i % n]
if y > min(p1y, p2y):
if y <= max(p1y, p2y):
if x <= max(p1x, p2x):
if p1y != p2y:
xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x, p1y = p2x, p2y
return inside
def generate_grids(polygons_wgs84: List[List[Tuple[float, float]]],
grid_size: float,
spacing: float,
utm_crs: str,
transformer_to_utm,
transformer_to_wgs) -> List[Dict]:
polygons_utm = []
for poly_wgs in polygons_wgs84:
poly_utm = [transformer_to_utm.transform(lon, lat) for lon, lat in poly_wgs]
polygons_utm.append(poly_utm)
all_utm_points = [p for poly in polygons_utm for p in poly]
min_x = min(p[0] for p in all_utm_points)
max_x = max(p[0] for p in all_utm_points)
min_y = min(p[1] for p in all_utm_points)
max_y = max(p[1] for p in all_utm_points)
print(f"Grid generation boundary: X=[{min_x:.2f}, {max_x:.2f}], Y=[{min_y:.2f}, {max_y:.2f}]")
print(f"Area size: {max_x-min_x:.2f}m x {max_y-min_y:.2f}m")
grids = []
grid_id = 0
y = min_y
row = 0
while y < max_y:
x = min_x
col = 0
while x < max_x:
center_x = x + grid_size / 2
center_y = y + grid_size / 2
center_lon, center_lat = transformer_to_wgs.transform(center_x, center_y)
is_in_any_polygon = False
for poly_wgs in polygons_wgs84:
if point_in_polygon((center_lon, center_lat), poly_wgs):
is_in_any_polygon = True
break
if is_in_any_polygon:
nw_lon, nw_lat = transformer_to_wgs.transform(x, y + grid_size)
se_lon, se_lat = transformer_to_wgs.transform(x + grid_size, y)
grid = {
'id': grid_id,
'row': row,
'col': col,
'utm_nw': (x, y + grid_size),
'utm_se': (x + grid_size, y),
'wgs84_nw': (nw_lon, nw_lat),
'wgs84_se': (se_lon, se_lat),
'center_wgs84': (center_lon, center_lat)
}
grids.append(grid)
grid_id += 1
x += (grid_size + spacing)
col += 1
y += (grid_size + spacing)
row += 1
print(f"Generated {len(grids)} grids that overlap with input polygons")
return grids
def create_kml(grids: List[Dict], output_path: str):
kml_header = '''<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>Grid Boundaries</name>
<Style id="gridStyle">
<LineStyle>
<color>ff0000ff</color>
<width>2</width>
</LineStyle>
<PolyStyle>
<color>330000ff</color>
</PolyStyle>
</Style>
'''
kml_footer = ''' </Document>
</kml>'''
with open(output_path, 'w') as f:
f.write(kml_header)
for grid in grids:
nw_lon, nw_lat = grid['wgs84_nw']
se_lon, se_lat = grid['wgs84_se']
ne_lon, ne_lat = se_lon, nw_lat
sw_lon, sw_lat = nw_lon, se_lat
placemark = f''' <Placemark>
<name>Grid {grid['id']:06d}</name>
<description>Row: {grid['row']}, Col: {grid['col']}</description>
<styleUrl>#gridStyle</styleUrl>
<Polygon>
<outerBoundaryIs>
<LinearRing>
<coordinates>
{nw_lon},{nw_lat},0
{ne_lon},{ne_lat},0
{se_lon},{se_lat},0
{sw_lon},{sw_lat},0
{nw_lon},{nw_lat},0
</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
'''
f.write(placemark)
f.write(kml_footer)
print(f"KML file created: {output_path}")
def get_tile_bounds(tile_dir: str) -> Dict[str, Dict]:
tile_bounds = {}
las_files = list(Path(tile_dir).glob("*.las")) + list(Path(tile_dir).glob("*.laz"))
las_files = [f for f in las_files if not f.name.startswith("grid_")]
print(f"Scanning {len(las_files)} tiles for bounds...")
for las_file in las_files:
try:
with laspy.open(str(las_file)) as f:
header = f.header
tile_bounds[las_file.name] = {
'min_x': header.x_min,
'max_x': header.x_max,
'min_y': header.y_min,
'max_y': header.y_max
}
except Exception as e:
print(f"Error reading {las_file.name}: {e}")
print(f"Successfully scanned {len(tile_bounds)} tiles")
return tile_bounds
def scan_global_elevation_range(tile_dir: str, tile_bounds: Dict) -> Tuple[float, float]:
print("\n" + "="*60)
print("Scanning global elevation range from all tiles...")
print("="*60)
global_min_z = float('inf')
global_max_z = float('-inf')
tiles_processed = 0
for tile_file in tqdm(tile_bounds.keys(), desc="Scanning tiles", unit="tile"):
tile_path = os.path.join(tile_dir, tile_file)
try:
with laspy.open(tile_path) as f:
las = f.read()
if las.header.point_count > 0:
z = np.array(las.z)
tile_min = float(z.min())
tile_max = float(z.max())
global_min_z = min(global_min_z, tile_min)
global_max_z = max(global_max_z, tile_max)
tiles_processed += 1
except Exception as e:
print(f"Error reading {tile_file}: {e}")
continue
if global_min_z == float('inf') or global_max_z == float('-inf'):
print("Warning: Could not determine global elevation range, will use local ranges")
return None, None
print(f"\nGlobal elevation range from {tiles_processed} tiles:")
print(f" Min elevation: {global_min_z:.2f}m")
print(f" Max elevation: {global_max_z:.2f}m")
print(f" Range: {global_max_z - global_min_z:.2f}m")
return global_min_z, global_max_z
def find_overlapping_tiles(grid: Dict, tile_bounds: Dict) -> List[str]:
grid_min_x, grid_max_y = grid['utm_nw']
grid_max_x, grid_min_y = grid['utm_se']
overlapping = []
for tile_name, bounds in tile_bounds.items():
if not (bounds['max_x'] < grid_min_x or bounds['min_x'] > grid_max_x or
bounds['max_y'] < grid_min_y or bounds['min_y'] > grid_max_y):
overlapping.append(tile_name)
return overlapping
def crop_las_with_pdal(tile_files: List[str], grid: Dict, output_path: str, tile_dir: str) -> Dict:
try:
min_x, max_y = grid['utm_nw']
max_x, min_y = grid['utm_se']
input_files = [os.path.join(tile_dir, f) for f in tile_files]
pipeline = {
"pipeline": []
}
for input_file in input_files:
pipeline["pipeline"].append(input_file)
bounds_str = f"([{min_x}, {max_x}], [{min_y}, {max_y}])"
filters = [
{
"type": "filters.crop",
"bounds": bounds_str
}
]
if USE_VOXEL_FILTER and len(tile_files) > 1:
filters.append({
"type": "filters.voxelcenternearestneighbor",
"cell": VOXEL_SIZE
})
filters.append({
"type": "writers.las",
"filename": output_path,
"compression": "laszip" if OUTPUT_COMPRESSED else "none"
})
pipeline["pipeline"].extend(filters)
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
json.dump(pipeline, f, indent=2)
pipeline_file = f.name
try:
result = subprocess.run(
['pdal', 'pipeline', pipeline_file],
capture_output=True,
text=True,
timeout=300
)
if result.returncode != 0:
return {
'success': False,
'error': f"PDAL error: {result.stderr}",
'point_count': 0
}
if not os.path.exists(output_path):
return {
'success': False,
'error': 'Output file not created',
'point_count': 0
}
with laspy.open(output_path) as f:
point_count = f.header.point_count
return {
'success': True,
'point_count': point_count,
'tiles_used': tile_files
}
finally:
if os.path.exists(pipeline_file):
os.remove(pipeline_file)
except subprocess.TimeoutExpired:
return {
'success': False,
'error': 'PDAL pipeline timeout',
'point_count': 0
}
except Exception as e:
return {
'success': False,
'error': str(e),
'point_count': 0
}
def voxel_downsample_python(input_las: str, output_las: str, voxel_size: float) -> int:
with laspy.open(input_las) as f:
las = f.read()
x = np.array(las.x)
y = np.array(las.y)
z = np.array(las.z)
voxel_x = np.floor(x / voxel_size).astype(np.int32)
voxel_y = np.floor(y / voxel_size).astype(np.int32)
voxel_z = np.floor(z / voxel_size).astype(np.int32)
voxel_keys = np.column_stack([voxel_x, voxel_y, voxel_z])
unique_voxels, unique_indices = np.unique(voxel_keys, axis=0, return_index=True)
las_filtered = laspy.LasData(las.header)
las_filtered.points = las.points[unique_indices]
las_filtered.write(output_las)
return len(unique_indices)
def generate_bev_png(las_path: str, output_path: str, grid: Dict):
try:
with laspy.open(las_path) as f:
las = f.read()
if las.header.point_count == 0:
if DEBUG_MODE:
print(f" BEV: Empty point cloud")
img = Image.new('RGBA', (BEV_RESOLUTION, BEV_RESOLUTION), (0, 0, 0, 0) if BEV_TRANSPARENT_BG else (255, 255, 255, 255))
img.save(output_path)
return
x = np.array(las.x)
y = np.array(las.y)
minx = grid['utm_nw'][0]
maxx = grid['utm_se'][0]
miny = grid['utm_se'][1]
maxy = grid['utm_nw'][1]
px = ((x - minx) / (maxx - minx) * (BEV_RESOLUTION - 1)).astype(np.int32)
py = ((maxy - y) / (maxy - miny) * (BEV_RESOLUTION - 1)).astype(np.int32)
valid = (px >= 0) & (px < BEV_RESOLUTION) & (py >= 0) & (py < BEV_RESOLUTION)
px = px[valid]
py = py[valid]
if len(px) == 0:
if DEBUG_MODE:
print(f" BEV: No valid points")
img = Image.new('RGBA', (BEV_RESOLUTION, BEV_RESOLUTION), (0, 0, 0, 0) if BEV_TRANSPARENT_BG else (255, 255, 255, 255))
img.save(output_path)
return
if BEV_USE_RGB and hasattr(las, 'red'):
r = np.array(las.red)[valid] // 256
g = np.array(las.green)[valid] // 256
b = np.array(las.blue)[valid] // 256
else:
r = g = b = None
img_array = np.zeros((BEV_RESOLUTION, BEV_RESOLUTION, 4), dtype=np.uint8)
if not BEV_TRANSPARENT_BG:
img_array[:, :, :3] = 255
img_array[:, :, 3] = 255
if BEV_ADAPTIVE_POINT_SIZE:
density_map = np.zeros((BEV_RESOLUTION, BEV_RESOLUTION), dtype=np.int32)
for i in range(len(px)):
density_map[py[i], px[i]] += 1
density_smoothed = uniform_filter(density_map.astype(np.float32), size=BEV_DENSITY_WINDOW)
max_density = density_smoothed.max()
if max_density > 0:
density_normalized = density_smoothed / max_density
else:
density_normalized = density_smoothed
for i in range(len(px)):
if BEV_ADAPTIVE_POINT_SIZE:
density_value = density_normalized[py[i], px[i]]
point_size = int(BEV_POINT_SIZE_MIN + (BEV_POINT_SIZE_MAX - BEV_POINT_SIZE_MIN) * (1 - density_value))
else:
point_size = BEV_POINT_SIZE
half_size = point_size // 2
x_start = max(0, px[i] - half_size)
x_end = min(BEV_RESOLUTION, px[i] + half_size + 1)
y_start = max(0, py[i] - half_size)
y_end = min(BEV_RESOLUTION, py[i] + half_size + 1)
if BEV_OPACITY_MODE == "fixed":
alpha = int(BEV_POINT_OPACITY * 255)
else:
alpha = 255
if r is not None:
color = [r[i], g[i], b[i]]
else:
color = [0, 0, 0]
img_array[y_start:y_end, x_start:x_end, :3] = color
img_array[y_start:y_end, x_start:x_end, 3] = alpha
img = Image.fromarray(img_array)
img.save(output_path)
if DEBUG_MODE:
print(f" BEV: Saved to {output_path}")
except Exception as e:
print(f" BEV: Error generating BEV: {e}")
if DEBUG_MODE:
import traceback
traceback.print_exc()
img = Image.new('RGBA', (BEV_RESOLUTION, BEV_RESOLUTION), (0, 0, 0, 0) if BEV_TRANSPARENT_BG else (255, 255, 255, 255))
img.save(output_path)
def generate_dsm(las_path: str, output_geotiff: str, output_png: str, grid: Dict,
resolution: int = 1024, global_min_z: float = None, global_max_z: float = None) -> Dict:
try:
from osgeo import gdal, osr
with laspy.open(las_path) as f:
las = f.read()
if las.header.point_count == 0:
if DEBUG_MODE:
print(f" DSM: Empty point cloud")
return None
x = np.array(las.x)
y = np.array(las.y)
z = np.array(las.z)
minx = grid['utm_nw'][0]
maxx = grid['utm_se'][0]
miny = grid['utm_se'][1]
maxy = grid['utm_nw'][1]
cell_size_x = (maxx - minx) / resolution
cell_size_y = (maxy - miny) / resolution
px = ((x - minx) / (maxx - minx) * (resolution - 1)).astype(np.int32)
py = ((maxy - y) / (maxy - miny) * (resolution - 1)).astype(np.int32)
valid = (px >= 0) & (px < resolution) & (py >= 0) & (py < resolution)
px = px[valid]
py = py[valid]
z = z[valid]
if len(px) == 0:
if DEBUG_MODE:
print(f" DSM: No valid points")
return None
dsm = np.full((resolution, resolution), -9999.0, dtype=np.float32)
half_size = DSM_POINT_SIZE // 2
for i in range(len(px)):
cy, cx = py[i], px[i]
for dy in range(-half_size, half_size + 1):
for dx in range(-half_size, half_size + 1):
ny = cy + dy
nx = cx + dx
if 0 <= ny < resolution and 0 <= nx < resolution:
current_z = dsm[ny, nx]
if current_z == -9999.0 or z[i] > current_z:
dsm[ny, nx] = z[i]
mask = dsm != -9999.0
if not mask.any():
if DEBUG_MODE:
print(f" DSM: All cells empty")
return None
local_min_elevation = float(dsm[mask].min())
local_max_elevation = float(dsm[mask].max())
if DSM_USE_GLOBAL_RANGE and global_min_z is not None and global_max_z is not None:
use_min = global_min_z
use_max = global_max_z
if DEBUG_MODE:
print(f" DSM: Using global range {use_min:.2f}-{use_max:.2f}m (local: {local_min_elevation:.2f}-{local_max_elevation:.2f}m)")
else:
use_min = local_min_elevation
use_max = local_max_elevation
if DEBUG_MODE:
print(f" DSM: Using local range {use_min:.2f}-{use_max:.2f}m")
driver = gdal.GetDriverByName('GTiff')
dataset = driver.Create(output_geotiff, resolution, resolution, 1, gdal.GDT_Float32)
geotransform = (minx, cell_size_x, 0, maxy, 0, -cell_size_y)
dataset.SetGeoTransform(geotransform)
srs = osr.SpatialReference()
epsg_code = int(grid.get('utm_crs', 'EPSG:27700').split(':')[1]) if 'utm_crs' in grid else 27700
srs.ImportFromEPSG(epsg_code)
dataset.SetProjection(srs.ExportToWkt())
band = dataset.GetRasterBand(1)
band.SetNoDataValue(-9999.0)
band.WriteArray(dsm)
dataset.FlushCache()
dataset = None
dsm_normalized = np.where(dsm == -9999.0, 0,
np.clip((dsm - use_min) / (use_max - use_min), 0, 1) * 65535)
dsm_img = dsm_normalized.astype(np.uint16)
img = Image.fromarray(dsm_img)
img.save(output_png)
if DEBUG_MODE:
print(f" DSM: GeoTIFF and PNG saved")
return {
'min_elevation': local_min_elevation,
'max_elevation': local_max_elevation,
'global_min_used': use_min,
'global_max_used': use_max,
'resolution': resolution,
'cell_size_x': cell_size_x,
'cell_size_y': cell_size_y
}
except ImportError:
print(f" DSM: Error - GDAL not installed. Install with: pip install gdal")
return None
except Exception as e:
print(f" DSM: Error - {e}")
if DEBUG_MODE:
import traceback
traceback.print_exc()
return None
def check_grid_already_processed(grid_id: int, output_dir: str) -> Dict:
file_ext = ".laz" if OUTPUT_COMPRESSED else ".las"
output_las = os.path.join(output_dir, f"grid_{grid_id:06d}{file_ext}")
output_bev = os.path.join(output_dir, f"grid_{grid_id:06d}_bev.png")
output_log = os.path.join(output_dir, f"grid_{grid_id:06d}.json")
required_files = [output_las, output_bev, output_log]
if GENERATE_DSM:
output_dsm_tif = os.path.join(output_dir, f"grid_{grid_id:06d}_dsm.tif")
output_dsm_png = os.path.join(output_dir, f"grid_{grid_id:06d}_dsm.png")
required_files.extend([output_dsm_tif, output_dsm_png])
if all(os.path.exists(f) for f in required_files):
try:
with open(output_log, 'r') as f:
log_data = json.load(f)
if all(os.path.getsize(f) > 0 for f in required_files):
return {
'grid_id': grid_id,
'status': 'success',
'point_count': log_data.get('point_count', 0),
'tiles_used': len(log_data.get('tiles_used', [])),
'resumed': True
}
except Exception as e:
if DEBUG_MODE:
tqdm.write(f" DEBUG: Failed to read log for grid {grid_id}: {e}")
return None
return None
def process_single_grid(grid: Dict, tile_bounds: Dict, tile_dir: str, output_dir: str,
utm_crs: str, global_min_z: float = None, global_max_z: float = None) -> Dict:
grid_id = grid['id']
if RESUME_MODE and not FORCE_REPROCESS:
existing_result = check_grid_already_processed(grid_id, output_dir)
if existing_result:
return existing_result
if DEBUG_MODE:
print(f"\n DEBUG: Grid bounds UTM: NW={grid['utm_nw']}, SE={grid['utm_se']}")
overlapping_tiles = find_overlapping_tiles(grid, tile_bounds)
if DEBUG_MODE:
print(f" DEBUG: Found {len(overlapping_tiles)} overlapping tiles: {overlapping_tiles[:3]}...")
if not overlapping_tiles:
return {
'grid_id': grid_id,
'status': 'no_tiles',
'message': 'No overlapping tiles found'
}
file_ext = ".laz" if OUTPUT_COMPRESSED else ".las"
output_las = os.path.join(output_dir, f"grid_{grid_id:06d}{file_ext}")
output_bev = os.path.join(output_dir, f"grid_{grid_id:06d}_bev.png")
output_log = os.path.join(output_dir, f"grid_{grid_id:06d}.json")
crop_result = crop_las_with_pdal(overlapping_tiles, grid, output_las, tile_dir)
if not crop_result['success']:
error_msg = crop_result.get('error', 'Unknown error')
return {
'grid_id': grid_id,
'status': 'failed',
'message': error_msg,
'tiles_checked': overlapping_tiles
}
if crop_result['point_count'] == 0:
return {
'grid_id': grid_id,
'status': 'empty',
'message': 'No points in cropped area',
'tiles_used': overlapping_tiles
}
if PYTHON_VOXEL_DEDUP and len(overlapping_tiles) > 1:
temp_output = output_las + ".temp"
os.rename(output_las, temp_output)
final_count = voxel_downsample_python(temp_output, output_las, VOXEL_SIZE)
os.remove(temp_output)
crop_result['point_count'] = final_count
if DEBUG_MODE:
print(f" DEBUG: Python voxel downsampled to {final_count} points")
generate_bev_png(output_las, output_bev, grid)
dsm_info = None
if GENERATE_DSM:
output_dsm_tif = os.path.join(output_dir, f"grid_{grid_id:06d}_dsm.tif")
output_dsm_png = os.path.join(output_dir, f"grid_{grid_id:06d}_dsm.png")
grid_with_crs = grid.copy()
grid_with_crs['utm_crs'] = utm_crs
dsm_info = generate_dsm(output_las, output_dsm_tif, output_dsm_png, grid_with_crs,
DSM_RESOLUTION, global_min_z, global_max_z)
log_data = {
'grid_id': grid_id,
'row': grid['row'],
'col': grid['col'],
'utm_nw': grid['utm_nw'],
'utm_se': grid['utm_se'],
'wgs84_nw': grid['wgs84_nw'],
'wgs84_se': grid['wgs84_se'],
'point_count': crop_result['point_count'],
'tiles_used': crop_result['tiles_used'],
'output_files': {
'las': os.path.basename(output_las),
'bev': os.path.basename(output_bev)
}
}
if GENERATE_DSM and dsm_info:
log_data['elevation'] = {
'local_min_elevation': dsm_info['min_elevation'],
'local_max_elevation': dsm_info['max_elevation'],
'global_min_used': dsm_info['global_min_used'],
'global_max_used': dsm_info['global_max_used'],
'elevation_range': dsm_info['max_elevation'] - dsm_info['min_elevation']
}
log_data['output_files']['dsm_geotiff'] = os.path.basename(output_dsm_tif)
log_data['output_files']['dsm_png'] = os.path.basename(output_dsm_png)
with open(output_log, 'w') as f:
json.dump(log_data, f, indent=2)
return {
'grid_id': grid_id,
'status': 'success',
'point_count': crop_result['point_count'],
'tiles_used': len(overlapping_tiles)
}
def main():
os.makedirs(OUTPUT_DIR, exist_ok=True)
if os.path.abspath(OUTPUT_DIR) == os.path.abspath(TILE_DIR):
print("ERROR: OUTPUT_DIR and TILE_DIR must be different!")
print(f"OUTPUT_DIR: {os.path.abspath(OUTPUT_DIR)}")
print(f"TILE_DIR: {os.path.abspath(TILE_DIR)}")
print("Please set OUTPUT_DIR to a different directory to avoid confusion.")
return
print("="*60)
print("STEP 1: Reading LAS boundaries and generating grids")
print("="*60)
polygons, utm_crs = parse_las_boundaries(INPUT_LAS_FILES, TILE_DIR)
transformer_to_utm = Transformer.from_crs("EPSG:4326", utm_crs, always_xy=True)
transformer_to_wgs = Transformer.from_crs(utm_crs, "EPSG:4326", always_xy=True)
grids = generate_grids(polygons, GRID_SIZE, GRID_SPACING,
utm_crs, transformer_to_utm, transformer_to_wgs)
print("\n" + "="*60)
print("STEP 2: Generating KML visualization")
print("="*60)
kml_output = os.path.join(OUTPUT_DIR, "output_grids.kml")
create_kml(grids, kml_output)
print("\n" + "="*60)
print("STEP 3: Scanning all LAS tiles")
print("="*60)
tile_bounds = get_tile_bounds(TILE_DIR)
if not tile_bounds:
print("ERROR: No valid tiles found!")
return
global_min_z = None
global_max_z = None
if GENERATE_DSM and DSM_USE_GLOBAL_RANGE:
global_min_z, global_max_z = scan_global_elevation_range(TILE_DIR, tile_bounds)
print("\n" + "="*60)
print("STEP 4: Processing grids and generating outputs")
print("="*60)
grids_to_process = grids[:TEST_MODE_LIMIT] if TEST_MODE_LIMIT else grids
if TEST_MODE_LIMIT:
print(f"\n*** TEST MODE: Processing only first {len(grids_to_process)} grids ***\n")
else:
print(f"\nProcessing all {len(grids_to_process)} grids\n")
if RESUME_MODE and not FORCE_REPROCESS:
print(f"*** RESUME MODE: Skipping already processed grids ***\n")
elif FORCE_REPROCESS:
print(f"*** FORCE REPROCESS: Reprocessing all grids ***\n")
if GENERATE_DSM:
print(f"DSM Configuration:")
print(f" Resolution: {DSM_RESOLUTION}x{DSM_RESOLUTION}")
print(f" Point size: {DSM_POINT_SIZE}x{DSM_POINT_SIZE} pixels per point")
print(f" Use global range: {DSM_USE_GLOBAL_RANGE}")
if DSM_USE_GLOBAL_RANGE and global_min_z is not None:
print(f" Global range: {global_min_z:.2f}m - {global_max_z:.2f}m\n")
results = []
resumed_count = 0
processed_count = 0
with tqdm(total=len(grids_to_process), desc="Processing grids", unit="grid") as pbar:
for i, grid in enumerate(grids_to_process):
grid_id = grid['id']
pbar.set_description(f"Processing grid {grid_id:06d}")
result = process_single_grid(grid, tile_bounds, TILE_DIR, OUTPUT_DIR, utm_crs,
global_min_z, global_max_z)
results.append(result)
if result.get('resumed', False):
resumed_count += 1
tqdm.write(f"Grid {grid_id:06d}: RESUMED - {result.get('point_count', 0):,} points (skipped)")
else:
processed_count += 1
if result['status'] == 'failed':
tqdm.write(f"Grid {grid_id:06d}: FAILED - {result.get('message', 'Unknown error')}")
elif result['status'] == 'success':
tqdm.write(f"Grid {grid_id:06d}: SUCCESS - {result.get('point_count', 0):,} points from {result.get('tiles_used', 0)} tiles")
elif result['status'] == 'empty':
tqdm.write(f"Grid {grid_id:06d}: EMPTY - No points in area")
elif result['status'] == 'no_tiles':
tqdm.write(f"Grid {grid_id:06d}: NO TILES - No overlapping tiles found")
pbar.update(1)
print("\n" + "="*60)
print("STEP 5: Generating final summary")
print("="*60)
summary = {
'config': {
'grid_size_m': GRID_SIZE,
'grid_spacing_m': GRID_SPACING,
'voxel_size_m': VOXEL_SIZE,
'use_voxel_filter': USE_VOXEL_FILTER,
'python_voxel_dedup': PYTHON_VOXEL_DEDUP,
'output_compressed': OUTPUT_COMPRESSED,
'bev_point_size': BEV_POINT_SIZE,
'bev_transparent_bg': BEV_TRANSPARENT_BG,
'bev_use_rgb': BEV_USE_RGB,
'bev_point_opacity': BEV_POINT_OPACITY,
'bev_opacity_mode': BEV_OPACITY_MODE,
'bev_adaptive_point_size': BEV_ADAPTIVE_POINT_SIZE,
'bev_point_size_min': BEV_POINT_SIZE_MIN,
'bev_point_size_max': BEV_POINT_SIZE_MAX,
'bev_density_window': BEV_DENSITY_WINDOW,
'generate_dsm': GENERATE_DSM,
'dsm_resolution': DSM_RESOLUTION,
'dsm_point_size': DSM_POINT_SIZE,
'dsm_use_global_range': DSM_USE_GLOBAL_RANGE,
'global_elevation_range': {
'min': global_min_z,
'max': global_max_z
} if global_min_z is not None else None,
'utm_crs': utm_crs,
'test_mode': TEST_MODE_LIMIT is not None,
'test_mode_limit': TEST_MODE_LIMIT,
'resume_mode': RESUME_MODE,
'force_reprocess': FORCE_REPROCESS
},
'statistics': {
'total_grids_generated': len(grids),
'grids_processed': len(grids_to_process),
'newly_processed': processed_count,
'resumed_skipped': resumed_count,
'successful': sum(1 for r in results if r['status'] == 'success'),
'failed': sum(1 for r in results if r['status'] == 'failed'),
'empty': sum(1 for r in results if r['status'] == 'empty'),
'no_tiles': sum(1 for r in results if r['status'] == 'no_tiles')
},
'results': results
}
summary_path = os.path.join(OUTPUT_DIR, "processing_summary.json")
with open(summary_path, 'w') as f:
json.dump(summary, f, indent=2)
print(f"\nSummary saved to: {summary_path}")
print(f"KML visualization: {kml_output}")
if TEST_MODE_LIMIT:
print(f"Test mode: Processed {len(grids_to_process)}/{len(grids)} grids")
if RESUME_MODE and resumed_count > 0:
print(f"Resumed: Skipped {resumed_count} already processed grids")
print(f"Newly processed: {processed_count} grids")
print(f"Success: {summary['statistics']['successful']}/{len(grids_to_process)}")
print("\nProcessing complete!")
if __name__ == "__main__":
main()