How to Split a Bog Image into Smaller Pieces Using GDAL and Python?

Estimated read time 2 min read

To split a big image into smaller pieces using GDAL and Python, you can use the gdal_translate command with the -srcwin option to specify the size and location of each piece. Here’s an example:

import os
import subprocess

# Open the input image using GDAL
input_file = 'big_image.tif'
dataset = gdal.Open(input_file)

# Get the size of the input image
width = dataset.RasterXSize
height = dataset.RasterYSize

# Set the size of the output tiles
tile_width = 1000
tile_height = 1000

# Loop over the input image and extract tiles
for i in range(0, width, tile_width):
    for j in range(0, height, tile_height):
        # Set the output file name
        output_file = f'tile_{i}_{j}.tif'

        # Extract the tile using gdal_translate
        command = f"gdal_translate -of GTIFF -srcwin {i}, {j}, {tile_width}, {tile_height} {input_file} {output_file}"
        subprocess.call(command, shell=True)

# Close the dataset
dataset = None

In this code, the gdal module is used to open the input image, and its size is obtained using the RasterXSize and RasterYSize properties. The tile_width and tile_height variables are used to set the size of each output tile. The code then loops over the input image and uses the gdal_translate command to extract tiles of the specified size. The output tiles are named based on their position in the input image, and saved as GeoTIFF files. Finally, the input dataset is closed using the None value.

You can customize the code by modifying the input and output file names, the size and number of output tiles, and the format of the output files based on your specific needs.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply