Reputation: 21
I've been trying to clip a raster file with a corresponding shape file using gdal Warp. However, I am encountering an error as follows:
<osgeo.gdal.Dataset; proxy of <Swig Object of type 'GDALDatasetShadow *' at 0x7f30542b86c0> >
from osgeo import gdal
rasin = "location of raster file.tif"
output = "destination of clipped raster file.tif"
shpin = "location of shapefile.shp"
gdal.Warp(output, rasin, cutlineDSName = shpin, format="GTiff", cropToCutline = True)
Upvotes: 1
Views: 8598
Reputation: 9
rasterio
will be a good choice.
import fiona
import rasterio
import rasterio.mask
src_raster_path = r'LC09_L2SP_007025_20220703_20220705_02_T1_SR_B2.TIF'
shp_file_path = "water_polygons.shp"
output_raster_path = src_raster_path[:-3] + 'water_masked.tif'
with fiona.open(shp_file_path, "r") as shapefile:
shapes = [feature["geometry"] for feature in shapefile]
with rasterio.open(src_raster_path) as src:
out_image, out_transform = rasterio.mask.mask(src, shapes, crop=True)
out_meta = src.meta
out_meta.update({"driver": "GTiff",
"height": out_image.shape[1],
"width": out_image.shape[2],
"transform": out_transform})
with rasterio.open(output_raster_path, "w", **out_meta) as dest:
dest.write(out_image)
Upvotes: 0