以下是使用Python代码在QGIS中按照矢量范围批量裁剪遥感影像的详细步骤:
# Import required libraries
import os
from qgis.core import (QgsVectorLayer, QgsProject, QgsRasterLayer,
QgsRectangle, QgsRasterFileWriter)
# Define the path to the vector layer containing the clipping polygons
vector_path = "/path/to/vector/layer.shp"
# Define the path to the directory containing the raster images to clip
image_dir = "/path/to/image/directory"
# Load the vector layer
vector_layer = QgsVectorLayer(vector_path, "Clipping Polygons", "ogr")
# Get the extent of the vector layer
extent = vector_layer.extent()
# Loop through all files in the image directory
for file_name in os.listdir(image_dir):
# Check if file is a raster image
if file_name.endswith(".tif"):
# Define the path to the input raster image
input_path = os.path.join(image_dir, file_name)
# Load the raster layer
raster_layer = QgsRasterLayer(input_path, file_name)
# Set the extent of the raster layer to match the vector layer
raster_layer.setExtent(extent)
# Clip the raster layer using the vector layer
output_path = os.path.join(image_dir, f"{file_name[:-4]}_clipped.tif")
writer = QgsRasterFileWriter(output_path)
writer.clipRasterByExtent(raster_layer, extent, True)
# Refresh the map canvas
iface.mapCanvas().refresh()
这段代码将加载矢量图层,获取其范围,并遍历指定目录中的所有遥感影像文件。对于每个遥感影像文件,代码将加载该文件作为栅格图层,并将其范围设置为与矢量图层相同。然后,代码将使用矢量图层裁剪栅格图层,并将输出保存到与输入文件相同的目录中,但文件名以“_clipped”结尾。最后,代码将刷新QGIS地图画布以显示新的裁剪栅格图层。