Last active
October 30, 2020 17:40
-
-
Save rpitonak/7c57b3dff6b7dbd87829034fe25a4fd6 to your computer and use it in GitHub Desktop.
Split GeoTiff to multiple tiff files (chunks) using Python3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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