11import os
2+ import numpy as np
23from osgeo import gdal
34
45def merge_tifs (subdir_path ):
56 # Get a list of all .tif files in the subdirectory
67 tif_files = [os .path .join (subdir_path , file ) for file in os .listdir (subdir_path ) if file .endswith ('.tif' )]
7-
8+
89 # If there are .tif files in the subdirectory, merge them
910 if tif_files :
1011 # Change the output file path to be one directory up
1112 parent_dir = os .path .dirname (subdir_path )
1213 output_file = os .path .join (parent_dir , f"{ os .path .basename (subdir_path )} .tif" )
14+
15+ # Step 1: Build VRT and merge tiles into temporary file
16+ temp_output = output_file + '.tmp.tif'
1317 vrt = gdal .BuildVRT ('' , tif_files )
14- gdal .Translate (output_file , vrt , options = '-co COMPRESS=DEFLATE -co PREDICTOR=2 -co ZLEVEL=9' )
15- vrt = None
18+ gdal .Translate (temp_output , vrt , options = '-co COMPRESS=DEFLATE -co PREDICTOR=2 -co ZLEVEL=9' )
19+ vrt = None
20+
21+ # Step 2: Process the merged file to convert negatives to 0 and set nodata=0
22+ print (f"Processing { os .path .basename (subdir_path )} : converting negative values to 0 and setting nodata=0" )
23+
24+ # Open the temporary file
25+ src_ds = gdal .Open (temp_output , gdal .GA_ReadOnly )
26+ if src_ds is None :
27+ print (f"Error: Could not open { temp_output } " )
28+ return
29+
30+ # Get raster properties
31+ driver = gdal .GetDriverByName ('GTiff' )
32+ cols = src_ds .RasterXSize
33+ rows = src_ds .RasterYSize
34+ bands = src_ds .RasterCount
35+ projection = src_ds .GetProjection ()
36+ geotransform = src_ds .GetGeoTransform ()
37+
38+ # Create output file with nodata=0
39+ dst_ds = driver .Create (output_file , cols , rows , bands , gdal .GDT_Float32 ,
40+ options = ['COMPRESS=DEFLATE' , 'PREDICTOR=2' , 'ZLEVEL=9' ])
41+ dst_ds .SetProjection (projection )
42+ dst_ds .SetGeoTransform (geotransform )
43+
44+ # Process each band
45+ for band_idx in range (1 , bands + 1 ):
46+ src_band = src_ds .GetRasterBand (band_idx )
47+ data = src_band .ReadAsArray ()
48+
49+ # Convert negative values to 0
50+ data = np .where (data < 0 , 0 , data )
51+
52+ # Write processed data to output
53+ dst_band = dst_ds .GetRasterBand (band_idx )
54+ dst_band .WriteArray (data )
55+ dst_band .SetNoDataValue (0 ) # Set 0 as nodata
56+ dst_band .FlushCache ()
57+
58+ # Close datasets
59+ src_ds = None
60+ dst_ds = None
61+
62+ # Remove temporary file
63+ try :
64+ os .remove (temp_output )
65+ except Exception as e :
66+ print (f"Warning: Could not remove temporary file { temp_output } : { e } " )
67+
68+ print (f"Completed { os .path .basename (subdir_path )} : output saved to { output_file } " )
0 commit comments