How to split a raster in several tiles using QGIS or Python (GDAL)

This task is based on my answer to this question poped up on gis.stackexchange.com.

Starting from a raster layer, the goal for this task is to split it in several tiles for further processing. We can do this task by directly using QGIS, or even with Python (GDAL).

More in detail, we want to split a 5×5 m raster layer (see image below) having 500 columns and 700 rows. For the sake of simplicity, we want to obtain 100 new tiles, so each one of them will have 50 columns and 70 rows (these parameters are randomly chosen, so you obviously need to adapt them to your specific case).

input


Solution using QGIS

In QGIS you may create a VRT mosaic.

Please follow this procedure (see the image below):

  1. Load the raster in the Layers Panel;
  2. Right-click on it and choose Save As...;
  3. Check the Create VRT option;
  4. Choose the folder where your outputs will be saved;
  5. Set the extent (if you want to work on the whole raster, don’t modify anything);
  6. Choose if using the current resolution (I suggest to leave it as default);
  7. Set the max number of columns and rows;
  8. Press the OK button.

dialog

The using of the parameters in the above dialog will lead to the creation of the tiles in the specified folder:

folder.PNG


Solution using Python (GDAL)

The same result could be obtained with the using of GDAL (gdal_translate).

With reference to the same parameters, we may use this script:

import os, gdal

in_path = 'C:/Users/Marco/Desktop/'
input_filename = 'dtm_5.tif'

out_path = 'C:/Users/Marco/Desktop/output_folder/'
output_filename = 'tile_'

tile_size_x = 50
tile_size_y = 70

ds = gdal.Open(in_path + input_filename)
band = ds.GetRasterBand(1)
xsize = band.XSize
ysize = band.YSize

for i in range(0, xsize, tile_size_x):
    for j in range(0, ysize, tile_size_y):
        com_string = "gdal_translate -of GTIFF -srcwin " + str(i)+ ", " + str(j) + ", " + str(tile_size_x) + ", " + str(tile_size_y) + " " + str(in_path) + str(input_filename) + " " + str(out_path) + str(output_filename) + str(i) + "_" + str(j) + ".tif"
        os.system(com_string)

Regardless of the method used, this will be the result:

tiled.png

Note: The result looks weird just because the style of each image fits itself to the distribution of values per image (but the data are perfectly fine).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s