SmartCane/python_app/python_scripts/old/test_merge.py

50 lines
2.1 KiB
Python

from osgeo import gdal
from pathlib import Path
import numpy as np
# Test merging with proper options
BASE_PATH_SINGLE_IMAGES = Path(r"C:\Users\timon\Resilience BV\4020 SCane ESA DEMO - Documenten\General\4020 SCDEMO Team\4020 TechnicalData\WP3\smartcane_v2\smartcane\laravel_app\storage\app\aura\cloud_test_single_images")
folder_for_virtual_raster = Path(r"C:\Users\timon\Resilience BV\4020 SCane ESA DEMO - Documenten\General\4020 SCDEMO Team\4020 TechnicalData\WP3\smartcane_v2\smartcane\laravel_app\storage\app\aura\cloud_test_merged_virtual")
folder_for_merged_tifs = Path(r"C:\Users\timon\Resilience BV\4020 SCane ESA DEMO - Documenten\General\4020 SCDEMO Team\4020 TechnicalData\WP3\smartcane_v2\smartcane\laravel_app\storage\app\aura\cloud_test_merged_tif")
slot = "2025-10-17"
# List downloaded tiles
file_list = [str(x / "response.tiff") for x in Path(BASE_PATH_SINGLE_IMAGES / slot).iterdir() if x.is_dir()]
print(f"Found {len(file_list)} tiles")
vrt_path = str(folder_for_virtual_raster / f"test_merged_{slot}.vrt")
output_path = str(folder_for_merged_tifs / f"test_{slot}.tif")
# Create virtual raster with proper options
print("Creating VRT...")
vrt_options = gdal.BuildVRTOptions(
resolution='highest',
separate=False,
addAlpha=False
)
vrt = gdal.BuildVRT(vrt_path, file_list, options=vrt_options)
vrt = None
# Convert to GeoTIFF with proper options
print("Converting to GeoTIFF...")
translate_options = gdal.TranslateOptions(
creationOptions=['COMPRESS=LZW', 'TILED=YES', 'BIGTIFF=IF_SAFER']
)
gdal.Translate(output_path, vrt_path, options=translate_options)
# Check the result
print(f"\nChecking merged file: {output_path}")
ds = gdal.Open(output_path)
print(f" Size: {ds.RasterXSize} x {ds.RasterYSize}")
print(f" Bands: {ds.RasterCount}")
for i in range(1, min(6, ds.RasterCount + 1)):
b = ds.GetRasterBand(i).ReadAsArray()
band_name = ["Red", "Green", "Blue", "NIR", "UDM1"][i-1] if i <= 5 else f"Band{i}"
print(f" {band_name}: Min={np.nanmin(b):.4f}, Max={np.nanmax(b):.4f}, Mean={np.nanmean(b):.4f}, Non-zero={((b > 0).sum() / b.size * 100):.2f}%")
ds = None
print("\n✓ Test merge complete!")