I want to clip raster using for mask other raster and I have find this question and I try to follow this code:

import gdal
from gdalconst import GA_ReadOnly

data = gdal.Open('img_mask.tif', GA_ReadOnly)
geoTransform = data.GetGeoTransform()
minx = geoTransform[0]
maxy = geoTransform[3]
maxx = minx + geoTransform[1] * data.RasterXSize
miny = maxy + geoTransform[5] * data.RasterYSize
call('gdal_translate -projwin ' + ' '.join([str(x) for x in [minx, maxy, maxx, miny]]) + ' -of GTiff img_orig.tif img_out.tif', shell=True)

But that code doesn't working the output TIFF have some extent with original TIFF against the clip doesn't work. Any idea?

  • Are you getting any error messages? Did you read the comment? If your mask and your input raster are in different coordinate reference systems the -projwin is not on the raster... there is an option for a different CRS -projwin_srs srs_def for use with -projwin if your mask raster is different, you can use CRS = data.GetProjection() then include '-projwin_srs {}'.format(CRS.ExportToWkt()) to pass the parameter to your call. Have a read of gdal.org/gdal_tutorial.html for some background (ignore the C/C++ unless you wish to program GDAL for C). Sep 30, 2018 at 10:59

1 Answer 1


You should use gdal.Translate method. Something like the following should work.

from osgeo import gdal
from gdalconst import GA_ReadOnly

maskDs = gdal.Open('myMask.tif', GA_ReadOnly)# your mask raster
geoTransform = maskDs.GetGeoTransform()
minx = geoTransform[0]
maxy = geoTransform[3]
maxx = minx + geoTransform[1] * maskDs.RasterXSize
miny = maxy + geoTransform[5] * maskDs.RasterYSize

data=gdal.Open('myRaster.tif', GA_ReadOnly) #Your data the one you want to clip
output='output.tif' #output file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.