I clipped a raster file through a shapefile. Now i want to clip that raster file through each features of shapefile. If there are 5 feature in that shp i wanted to clip the raster through those 5 features and i should get 5seperate rasters as per features. I'm using rasterio and fiona for that. Is there a way to do that?
Asked
Active
Viewed 1,077 times
0
-
Welcome to SO. Please read [how-to-ask](https://stackoverflow.com/help/how-to-ask), [minimal-reproducible-example](https://stackoverflow.com/help/minimal-reproducible-example) and [editing-help](https://stackoverflow.com/editing-help), then update your question with specific details, simplified examples to support your explanation, and code/configuration/links you have tried so far. – Azhar Khan Aug 05 '22 at 05:33
2 Answers
0
Maybe you can start from here:
import rasterio
import Fiona
# Create a Raster object
raster = rasterio.Raster()
# Get the shapefile data
shapefile = open('shapefile.shp', 'r')
# Get the raster data
rasters = shapefile.shape.getData()
# Loop through the rasters and clip them to the features in the shapefile
for raster in rasters:
# Get the coordinates of the feature in the raster
featureX = raster.GetX()
featureY = raster.GetY()
# Clip the raster to the feature
raster.Clip(featureX, featureY)

c0d3x27
- 193
- 2
- 15
0
This works for me
#import libs
import rasterio
from rasterio import plot
from rasterio.mask import mask
from rasterio.plot import show
from matplotlib import pyplot
import fiona
import shapely
import geopandas as gpd
#raster file path
ras_fp = (r'Classification.tif')
#read shapefile
gdf = gpd.read_file('vill.shp')
# gdf.crs
names = [x for x in gdf['layer']] #get column value from shapefile
#read raster data
ras_data = rasterio.open(ras_fp)
#output path
out_raster_fp = '/output'
#save output files as per shapefile features
for i in range(len(gdf)):
geom = []
coord = shapely.geometry.mapping(gdf)["features"][i]["geometry"]
geom.append(coord)
with rasterio.open(ras_fp)as src:
out_image, out_transform = rasterio.mask.mask(src,geom,crop=True)
out_meta = src.meta
out_meta.update({'driver':'GTiff',
'height':out_image.shape[1],
'width':out_image.shape[2],
'transform':out_transform})
#file_path = ''
with rasterio.open(f'{out_raster_fp}/{names[i]}.tif','w',**out_meta)as
dest:
dest.write(out_image)

Asmita Guha
- 21
- 5