1

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?

Vince
  • 20,017
  • 15
  • 45
  • 64
hellas
  • 393
  • 7
  • 18
  • 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 https://www.gdal.org/gdal_tutorial.html for some background (ignore the C/C++ unless you wish to program GDAL for C). – Michael Stimson Sep 30 '18 at 10:59

1 Answers1

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
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) 
lcalisto
  • 83
  • 7