Certainly! Below is a Python script that uses the rasterio and geopandas libraries to read multiple raster files of Land Use Land Cover (LULC) yearwise from a folder, and clips each raster using a shapefile.
First, ensure you have the required libraries installed. You can install them using pip if you haven't already:
pip install rasterio geopandas shapely
Here is the script:
import os
import rasterio
from rasterio.mask import mask
import geopandas as gpd
import glob
def clip_rasters(raster_folder, shapefile_path, output_folder):
# Ensure the output folder exists
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Read the shapefile
shapefile = gpd.read_file(shapefile_path)
if shapefile.is_empty:
raise ValueError("Shapefile is empty")
# Get the crs from the shapefile
shape_crs = shapefile.crs
# Get a list of all raster files in the folder
raster_files = glob.glob(os.path.join(raster_folder, "*.tif")) # Adjust the extension if needed
for raster_path in raster_files:
# Extract the year from the filename
# Assuming the filenames are in the format "LULC_YYYY.tif"
# Adjust this according to your filename convention
filename = os.path.basename(raster_path)
year = filename.split('_')[1].split('.')[0]
# Open the raster file
with rasterio.open(raster_path) as src:
# Check if the raster and shapefile CRS match, if not, raise an error
if src.crs != shape_crs:
raise ValueError(f"CRS mismatch between raster {filename} and shapefile. "
f"Raster CRS: {src.crs}, Shapefile CRS: {shape_crs}")
# Clip the raster using the shapefile
out_image, out_transform = mask(src, shapefile.geometry, crop=True)
out_meta = src.meta.copy()
# Update the metadata
out_meta.update({
"driver": "GTiff",
"height": out_image.shape[1],
"width": out_image.shape[2],
"transform": out_transform,
})
# Define the output path
output_path = os.path.join(output_folder, f"clipped_LULC_{year}.tif")
# Write the clipped raster to the output file
with rasterio.open(output_path, "w", **out_meta) as dest:
dest.write(out_image)
print(f"Clipped and saved: {output_path}")
if __name__ == "__main__":
raster_folder = "path/to/your/raster/folder" # Change this to your raster folder path
shapefile_path = "path/to/your/shapefile.shp" # Change this to your shapefile path
output_folder= "path/to/your/output/folder" # Change this to your desired output folder path
clip_rasters(raster_folder, shapefile_path, output_folder)
Explanation:
- Import Libraries:
os: For handling directory and file operations.
rasterio: For reading and writing raster files.
geopandas: For reading and handling shapefiles.
glob: For finding all the pathnames matching a specified pattern.
- clip_rasters Function:
- Parameters:
raster_folder: Path to the folder containing the raster files.
shapefile_path: Path to the shapefile used for clipping.
output_folder: Path to the folder where the clipped rasters will be saved.
- Create Output Folder: Ensures the output folder exists; if not, it creates one.
- Read Shapefile: Loads the shapefile using
geopandas.
- List Raster Files: Uses
glob to find all .tif files in the raster folder. Adjust the extension if your rasters have a different one
- Loop Through Raster Files:
- Extract Year: Extracts the year from the filename. Adjust the splitting logic based on your filename convention.
- Open Raster: Opens the raster file using
rasterio.
- CRS Check: Ensures the Coordinate Reference System (CRS) of the raster matches the shapefile's CRS.
- Clip Raster: Clips the raster using the shapefile with
rasterio.mask.mask.
- Update Metadata: Updates the metadata of the clipped raster.
- Save Clipped Raster: Saves the clipped raster to the output folder with a new filename including the year.
- Main Block:
- Sets the paths for the raster folder, shapefile, and output folder.
- Calls the
clip_rasters function with the specified paths.
Usage
- Replace
"path/to/your/raster/folder", "path/to/your/shapefile.shp", and "path/to/your/output/folder" with the actual paths on your system.
- Run the script. It will read all the raster files in the specified folder, clip them using the provided shapefile, and save the clipped rasters in the output folder.