Here's a well-documented Python script that reads multiple LULC (Land Use/Land Cover) raster files year-wise from a folder, clips each of them using a shapefile, and saves the clipped outputs to a new directory.
✅ Overview of the Script
Input:
A folder containing multiple raster files (e.g., GeoTIFFs).
A shapefile used to clip the raster files.
Output:
Clipped versions of each raster, saved in a new output folder with a clipped_ prefix.
🧩 Libraries Used
os: For directory and file path manipulation.
rasterio: For reading and writing raster data.
rasterio.mask: To perform the clipping operation.
geopandas: For reading and reprojecting the shapefile.
shapely.geometry.mapping: To convert Shapely geometries into GeoJSON-like dictionaries.
📦 Script
python
import os
import rasterio
from rasterio.mask import mask
import geopandas as gpd
from shapely.geometry import mapping
# Define paths
raster_folder = 'path/to/raster/folder'
shapefile_path = 'path/to/shapefile.shp'
output_folder = 'path/to/output_folder'
# Create output directory if it doesn't exist
os.makedirs(output_folder, exist_ok=True)
# Loop through all raster files in the folder
for filename in os.listdir(raster_folder):
if filename.lower().endswith(('.tif', '.tiff', '.img', '.grd', '.rst')):
raster_path = os.path.join(raster_folder, filename)
with rasterio.open(raster_path) as src:
# Read shapefile
gdf = gpd.read_file(shapefile_path)
# Reproject shapefile to match the raster's coordinate reference system (CRS)
gdf_projected = gdf.to_crs(src.crs)
# Convert geometries to GeoJSON-like dictionary format
geoms = [mapping(geom) for geom in gdf_projected.geometry]
try:
# Clip the raster using the shapefile geometries
out_image, out_transform = mask(src, geoms, crop=True)
# Copy original metadata and update with new dimensions and transform
out_meta = src.meta.copy()
out_meta.update({
'height': out_image.shape[1],
'width': out_image.shape[2],
'transform': out_transform
})
# Define output file path
output_path = os.path.join(output_folder, f'clipped_{filename}')
# Write the clipped raster to a new file
with rasterio.open(output_path, 'w', **out_meta) as dest:
dest.write(out_image)
print(f"Successfully processed: {filename}")
except Exception as e:
print(f"Error processing {filename}: {e}")
📌 Key Notes
File Extensions: The script checks for common raster formats like .tif, .tiff, .img, etc. You can extend this list if needed.
CRS Handling: The shapefile is automatically reprojected to match the raster's CRS using geopandas.
Masking: The mask function from rasterio is used with crop=True, which ensures the output raster is cropped exactly to the shapefile's extent.
Error Handling: A try-except block is included to catch and report any issues during processing.
Output Naming: The clipped files are saved with a clipped_ prefix to distinguish them from the original files.
🧪 Example Output File Name
If the input file is lulc_2020.tif, the output will be: