Saturday, 1 June 2019

gdal - How to replicate gdalwarp -cutline in Python to cut out tif image based on the extents.kml file


In my python code I run the following command:


command = 'gdalwarp rgb.tif rgb_output_cut.tif -cutline extent.kml -dstnodata 0 -q'
os.system(command)

This cuts rgb.tif based on the extents specified in extent.kml and outputs a file called rgb_output_cut.tif. I would like to run this command without gdalwarp but instead with Python bindings. Is anyone familiar with this? Also, for the purposes of my task, having -dstnodata 0 is optional, it is just nice to have.


I found similar examples, however, they are just using gdalwarp for reprojection. For my case I'd like to cut out an extent.


Here, in my extent.kml file it is just a series of LinearRing Polygons, for example:



  

clampToGroundclampToGround-104.959386510378,39.7075208980859 -104.959394642483,39.7020277743643 -104.968738431214,39.7020465443243 -104.968779091739,39.7075083857725 -104.959386510378,39.7075208980859

Not, I must use gdal version 1.10.1.



Answer



Using the GDAL Python bindings (GDAL >= 2.1), it should be:


from osgeo import gdal

input_raster = "path/to/rgb.tif"

output_raster = "path/to/rgb_output_cut.tif"
input_kml = "path/to/extent.kml"

ds = gdal.Warp(output_raster,
input_raster,
format = 'GTiff',
cutlineDSName = input_kml,
cutlineLayer = 'extent',
dstNodata = 0)
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...