[GIS] Clip raster using mask other raster using Python GDAL

gdalpython

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?

Best Answer

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
projection=maskDs.GetProjectionRef()
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
gdal.Translate(output,data,format='GTiff',projWin=[minx,maxy,maxx,miny],outputSRS=projection)