GDAL.Warp() Raster Extent Increase – How to Prevent gdal.Warp() in Python from Increasing Raster’s Extent When Clipping to a Larger Shapefile

gdalgdalwarppygdalpython

I have a set of GeoTIFFs each covering a subset of a country that I want to clip to the coastline of that country. I have a single shapefile that defines the coastline of the country. As I have a number of GeoTIFFs to clip, I am trying to automate it using the GDAL Python API using the following:

clipped_plot = gdal.Warp(output_file, input_file, dstNodata=1.701410e+038,
                         cropToCutline=True, cutlineDSName=clip_file)
clipped_plot = None

The problem is that this creates an output file that covers the entire extent of the clipping shapefile, which is larger than the input GeoTIFF. This leaves large areas of unnecessary "no data" values and massively increases the file size of the output file.

I have used the GDAL command line tool that comes with QGIS to carry out the same procedure, but this does not have the same problem – the output file is limited by the input file's extent. This was the command line I used:

gdalwarp -dstnodata 1.701410e+038 -cutline clip_file input_file output_file

Is there a way to limit the output extent to be less than or equal to the input extent using GDAL in Python?

Best Answer

By your definition you must not use cropToCutline=True when the cropline is larger than the image but you would like to use it when the cropline extent is smaller than the image. I don't believe that there is ready made GDAL code for making this distinction but you must write your own. Maybe in your case with the coastline geometry you do not need to worry about the latter path and you can just use cropToCutline=False that is also the default.