怎么用Python进行遥感图像几何校正与投影转换
使用 rasterio 读取原始图像并获取其仿射变换参数,再结合 pyproj 定义源与目标坐标系,通过 warp.reproject 函数直接完成重采样、投影转换与几何校正的一体化操作。

理解仿射变换与坐标参考系
遥感影像的几何位置由仿射变换矩阵(Affine)确定,它将像素行列号映射为地理坐标。若忽略此参数或混淆 WGS84 与投影坐标系,会导致地图叠加错位。

rasterio 中的 transform 属性包含左上角坐标及像元尺寸,是后续重采样的基础。必须确保输入图像的 CRS 定义准确,否则 pyproj 无法执行正确的数学转换。
核心代码:一键重投影与校正
将完整脚本保存为 geo_correct.py,在终端运行 python geo_correct.py 即可生成校正后的输出文件。

import rasterio
from rasterio.warp import reproject, Resampling
from rasterio.transform import from_bounds
import pyproj
def correct_image(src_path, dst_path, target_crs="EPSG:3857"):
with rasterio.open(src_path) as src:
# 1. 读取元数据与数据
transform = src.transform
crs = src.crs
data = src.read(1)
# 2. 定义目标 CRS
dst_crs = pyproj.CRS.from_string(target_crs)
# 3. 计算新图像的仿射变换
# 这里简化处理:假设保持相同边界,实际需重新计算 bounds
new_transform, width, height = calculate_new_transform(src, dst_crs)
# 4. 执行重投影
dst_data = numpy.zeros((height, width), dtype=numpy.float32)
reproject(
source=data,
destination=dst_data,
src_transform=transform,
src_crs=crs,
dst_transform=new_transform,
dst_crs=dst_crs,
resampling=Resampling.bilinear
)
# 5. 写入新文件
with rasterio.open(
dst_path, 'w',
driver='GTiff',
height=height,
width=width,
count=1,
dtype=dst_data.dtype,
crs=dst_crs,
transform=new_transform
) as dst:
dst.write(dst_data, 1)
def calculate_new_transform(src, dst_crs):
# 简化版:实际项目中应使用 rasterio.warp.calculate_default_transform
from rasterio.warp import calculate_default_transform
transform, width, height = calculate_default_transform(
src.crs, dst_crs, src.width, src.height, *src.bounds
)
return transform, width, height
# 注意:需导入 numpy
import numpy
if __name__ == "__main__":
# 替换为你的实际文件路径
correct_image("input.tif", "output.tif")
程序成功运行时,会在当前目录生成 output.tif,其空间参考变为 Web Mercator (EPSG:3857)。若输入文件缺少 CRS 信息,rasterio 会抛出警告,此时需手动指定 src_crs。插值方式影响边缘平滑度,分类图务必改为 Resampling.nearest。
该程序利用 warp.reproject 处理内存中的数组,避免中间文件读写开销,适合快速批量处理。
处理非标准分辨率时的插值选择
当目标分辨率与源数据不一致时,需根据数据类型选择插值算法,否则会出现锯齿或模糊。
对于连续型数据(如高程),应使用双线性或三次卷积插值;对于分类数据(如土地利用),必须使用最近邻插值以保持类别整数不变。代码中通过 Resampling 枚举类指定具体策略。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









