Skip to main content
added 28 characters in body
Source Link
PolyGeo
  • 65.4k
  • 29
  • 114
  • 345

Thank you for your suggestions. I edited the Skript from Ilias Machairasscript from @IliasMachairas a little bit and finished with the following:

Thank you for your suggestions. I edited the Skript from Ilias Machairas a little bit and finished with the following:

I edited the script from @IliasMachairas a little bit and finished with the following:

Source Link
Robin
  • 21
  • 3

Thank you for your suggestions. I edited the Skript from Ilias Machairas a little bit and finished with the following:

import rasterio
import os
from rasterio.merge import merge
from rasterio.warp import calculate_default_transform, reproject, Resampling

def merge_tiff(tiff_files, output_file):
    print("Merging TIFF files...")
    try:
        src_files_to_mosaic = []
        for fp in tiff_files:
            src = rasterio.open(fp)
            src_files_to_mosaic.append(src)
        
        # Merge function from Rasterio
        mosaic, out_trans = merge(src_files_to_mosaic)
        
        # Metadata of the output file
        out_meta = src_files_to_mosaic[0].meta.copy()
        out_meta.update({
            "driver": "GTiff",
            "height": mosaic.shape[1],
            "width": mosaic.shape[2],
            "transform": out_trans
        })
        
        # Save the merged TIFF
        with rasterio.open(output_file, 'w', **out_meta) as dest:
            dest.write(mosaic)
        
        # Close all the source files
        for src in src_files_to_mosaic:
            src.close()
        print(f"Merged file saved to {output_file}")
    except Exception as e:
        print(f"Error during merging: {e}")

def resample_image(input_raster_path, output_raster_path, cell_size=30):
    print("Resampling image...")
    try:
        with rasterio.open(input_raster_path) as src:
            # Compute the new transform and dimensions
            transform, width, height = calculate_default_transform(
                src.crs, src.crs, src.width, src.height, *src.bounds, resolution=cell_size)
        
            # Define the new metadata
            new_meta = src.meta.copy()
            new_meta.update({
                'transform': transform,
                'width': width,
                'height': height,
                'crs': src.crs
            })
        
            # Resample the raster
            with rasterio.open(output_raster_path, 'w', **new_meta) as dst:
                for i in range(1, src.count + 1):
                    reproject(
                        source=rasterio.band(src, i),
                        destination=rasterio.band(dst, i),
                        src_transform=src.transform,
                        src_crs=src.crs,
                        dst_transform=transform,
                        dst_crs=src.crs,
                        resampling=Resampling.bilinear)  # Change to Resampling.nearest for nearest neighbor
            print(f"Resampled file saved to {output_raster_path}")
    except Exception as e:
        print(f"Error during resampling: {e}")

def process_geotiffs(input_folder):
    tiff_files = [os.path.join(input_folder, file) for file in os.listdir(input_folder) if file.endswith('.tif')]
    if not tiff_files:
        print("No TIFF files found in the input folder.")
        return
    
    output_folder = os.path.join(input_folder, 'outputs')
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    
    merged_output_file = os.path.join(output_folder, 'merged_image.tif')
    resampled_output_file = os.path.join(output_folder, 'merged_image_resampled.tif')
    
    merge_tiff(tiff_files, merged_output_file)
    resample_image(merged_output_file, resampled_output_file)

if __name__ == "__main__":
    print("Starting script...")
    input_folder = os.path.dirname(os.path.abspath(__file__))
    process_geotiffs(input_folder)
    print("Script completed.")

Now you can put the skript in the same folder with the GeoTIFF's and execute it. It will create a subfolder outputs automatically and store the results inside the folder. Make sure to install rasterio in your Python Environment before you execute it.