Tell me, is there the easiest way to trim a raster layer in python using a shapefile?

  • Give a small example of input and output - MaxU
  • What do you have in the arsenal? numpy, arcpy? - Eugene Dennis
  • Try asking a question on the subject segment gis.stackexchange.com - Eugene Dennis
  • In my set of modules there are gdal, numpy, georaster, etc. - Edu Gis

2 answers 2

Try (unfortunately without verification):

 import ogr import subprocess raster = r'raster.tif' shp = r'my.shp' ds = ogr.Open(shp) lyr = ds.GetLayer(0) lyr.ResetReading() ft = lyr.GetNextFeature() while ft: suffix_name = ft.GetFieldAsString('name') out_raster = raster.replace('.tif', '_%s.tif' % suffix_name.replace(' ', '_')) subprocess.call(['gdalwarp', raster, out_raster, '-cutline', shp, '-crop_to_cutline', '-cwhere', "'name'='%s'" % suffix_name]) ft = lyr.GetNextFeature() ds = None 
  • Thank you very much, I will try - Edu Gis

Thank you all for the hint! As a result, the issue was resolved using the RasterIO module:

 import fiona import rasterio from rasterio.tools.mask import mask with fiona.open("F:/SRB_Mosaic/003_Shapefiles/studyarea_0718_32642.shp", "r") as shapefile: geoms = [feature["geometry"] for feature in shapefile] with rasterio.open("F:/SRB_Mosaic/001_Initial_10m_images/Initial_data/T42TWM_20170525T061631_B03.jp2") as src: out_image, out_transform = mask(src, geoms, crop=True) out_meta = src.meta.copy() out_meta.update({"driver": "GTiff", "height": out_image.shape[1], "width": out_image.shape[2], "transform": out_transform}) with rasterio.open("F:/T42TWM_20170525T061631_B03clip.tif", "w", **out_meta) as dest: dest.write(out_image) 

The snag was in a different zone of the projection of the shapefile and raster layer. At first I brought them into one zone, then managed to apply the mask of the vector file to the raster. Good luck everyone!