Wednesday, 21 January 2015

Clipping tiff raster image using bounding box with GDAL in python


I would like to know how can I clip a raster image using a bounding box in python.



So far I can do it with gdal_translate:


gdal_translate -projwin -75.3 5.5 -73.5 3.7 -of GTiff original.tif new.tif

I tried:


import gdal
from gdalconst import *
src_filename = 'ori.tif'
dst_filename = 'new.tif'
src_ds = gdal.Open(src_filename, GA_ReadOnly)
format = "GTiff"

driver = gdal.GetDriverByName( format )
dst_ds = driver.CreateCopy( dst_filename, src_ds, 0, [ '-projwin=-75.3 5.5 -73.5 3.7'] )
dst_ds = None
src_ds = None

I know that the -projwin option should not be defined this way. I get the message:



Driver GTiff does not support -projwin creation option




Answer




Since GDAL 2.1 (more info here) GDAL and OGR utilities can be used as library functions, so this task is incredibly simple now:


from osgeo import gdal

ds = gdal.Open('original.tif')
ds = gdal.Translate('new.tif', ds, projWin = [-75.3, 5.5, -73.5, 3.7])
ds = None

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...