[ACCEPTED]-GTiff mask with shapefile in python with gdal, ogr, etc-ogr
This functionality is already incorporated 14 into the gdal command line utilities. Given 13 your case, i don't see any reason why you 12 want to do this yourself in Python.
You 11 can loop over the geomerties with OGR and 10 for each one call
gdalwarp with the appropriate 9 parameters.
import ogr import subprocess inraster = 'NE1_HR_LC_SR_W_DR\NE1_HR_LC_SR_W_DR.tif' inshape = '110m_cultural\ne_110m_admin_0_countries_lakes.shp' ds = ogr.Open(inshape) lyr = ds.GetLayer(0) lyr.ResetReading() ft = lyr.GetNextFeature() while ft: country_name = ft.GetFieldAsString('admin') outraster = inraster.replace('.tif', '_%s.tif' % country_name.replace(' ', '_')) subprocess.call(['gdalwarp', inraster, outraster, '-cutline', inshape, '-crop_to_cutline', '-cwhere', "'admin'='%s'" % country_name]) ft = lyr.GetNextFeature() ds = None
I have used some example data 8 from Natural Earth in the example above, for 7 Brazil the cutout looks like:
If you only 6 want to crop the image to the area of the 5 polygon and dont mask anything outside you 4 can transform the Shapefile so it contains 3 the envelope of the polygons. Or simply 2 loose the shapefile and call
-projwin to specify 1 the area of interest.
More Related questions