Skip to content

Instantly share code, notes, and snippets.

@rpitonak
Last active October 30, 2020 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpitonak/7c57b3dff6b7dbd87829034fe25a4fd6 to your computer and use it in GitHub Desktop.
Save rpitonak/7c57b3dff6b7dbd87829034fe25a4fd6 to your computer and use it in GitHub Desktop.
Split GeoTiff to multiple tiff files (chunks) using Python3
# Adapted from this StackOverflow answer: https://gis.stackexchange.com/a/14717
"""
Usage:
file_path = "/tmp/file.tiff"
split_tiff("/tmp/file.tiff", 256, 256)
The resulting output will be chunks /tmp/file_0_0.tiff ...
If you want to change the name of the output file feel free to tweak the code.
"""
import osgeo.gdal
def get_tiff_size(dset):
"""
Get width and height of the loaded GEOTiff
Usage:
dset = osgeo.gdal.Open("/tmp/file.tiff")
width, height = get_tiff_size(dset)
"""
width = dset.RasterXSize
height = dset.RasterYSize
return width, height
def split_tiff(input_file, tilesize_x, tilesize_y):
print(f"Processing file: {input_file}")
dset = osgeo.gdal.Open(input_file)
width, height = get_tiff_size(dset)
row = 0
col = 0
for i in range(0, width, tilesize_x):
for j in range(0, height, tilesize_y):
w = min(i + tilesize_x, width) - i
h = min(j + tilesize_y, height) - j
gdal_cmd = f'gdal_translate -of GTIFF -srcwin {i}, {j}, {w}, {h} "{input_file}" "{input_file.split(".tiff")[0]}_{col}_{row}.tiff"'
os.system(gdal_cmd)
col += 1
row += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment