import os import glob from osgeo import gdal def resize_geotiff(input_path, output_path, scale_factor): # Open the input geotiff file dataset = gdal.Open(input_path) if dataset is None: print(f"Error: Could not open {input_path}") return # Get the original dimensions original_width = dataset.RasterXSize original_height = dataset.RasterYSize # Calculate new dimensions new_width = int(original_width * scale_factor) new_height = int(original_height * scale_factor) # Create an output geotiff file driver = gdal.GetDriverByName("GTiff") output_dataset = driver.Create(output_path, new_width, new_height, dataset.RasterCount, dataset.GetRasterBand(1).DataType) # Copy projection and geotransform from the original dataset output_dataset.SetProjection(dataset.GetProjection()) output_dataset.SetGeoTransform(dataset.GetGeoTransform()) # Resize and copy each band for band_num in range(1, dataset.RasterCount + 1): band = dataset.GetRasterBand(band_num) resized_data = band.ReadAsArray(0, 0, original_width, original_height, new_width, new_height) output_band = output_dataset.GetRasterBand(band_num) output_band.WriteArray(resized_data) # Close the datasets dataset = None output_dataset = None print(f"{input_path} resized and saved as {output_path}") def main(input_folder, output_folder, scale_factor): # Create the output folder if it doesn't exist if not os.path.exists(output_folder): os.makedirs(output_folder) # Find all geotiff files in the input folder geotiff_files = glob.glob(os.path.join(input_folder, "*.tif")) for geotiff_file in geotiff_files: file_name = os.path.basename(geotiff_file) output_path = os.path.join(output_folder, file_name) resize_geotiff(geotiff_file, output_path, scale_factor) if __name__ == "__main__": input_folder = "kosher" output_folder = "kosher/new" scale_factor = 0.5 # 50% reduction main(input_folder, output_folder, scale_factor)