1

How do I clip a shapefile with a raster file with gdalwarp?

Input: a shapefile
Cutter: a raster file
Output: a cut shapefile

I can only find the answer of cutting the raster file by a shapefile but not vice versa.

nmtoken
  • 13,355
  • 5
  • 38
  • 87
Lion Lai
  • 258
  • 2
  • 11
  • 1
    related (the opposite) https://gis.stackexchange.com/questions/45053/gdalwarp-cutline-along-with-shapefile (maybe a clue?) – Mapperz Feb 04 '19 at 17:40
  • 1
    Do you want to cut by the extent of the raster? See Vector->Research Tool->Extract Layer Extent, and make an intersection Vector->Geoprocessing Tools->Intersection. – Zoltan Feb 04 '19 at 17:52
  • @Mapperz: I've tried to switch the shapefile and raster, but it doesn't work. – Lion Lai Feb 05 '19 at 10:56
  • @Zoltan: I know I can do it with qgis, but I am looking for a gdal function to do it. – Lion Lai Feb 05 '19 at 10:58

1 Answers1

1

Try to create the data extent of the raster e.g. with gdal-dans-scripts (apt install dans-gdal-scripts) by using gdal_trace_outline like (ndv is the no data value that will be not considered so if you need to clip with certain value you can create a mask before):

gdal_trace_outline clipper_image.tif -ndv 0 -dp-toler 10 -min-ring-area 10000  -no-donuts -ogr-out clipper_shape.shp  

Also you can try to vectorize your raster e.g. with gdal_polygonize.

And then clip with ogr2ogr:

ogr2ogr your_shape_to_be_clipped.shp -clipsrc clipper_shape.shp final_clip.shp
K. Stopa
  • 161
  • 4