用 RPC 模型校正卫星影像并输出 GeoTIFF。

解读

国内遥感岗位面试时,考官抛出“用 RPC 模型校正卫星影像并输出 GeoTIFF”,并不是让你手写一套完整摄影测量软件,而是考察三件事:

  1. 是否知道 Pillow 在整链路中的定位——它只负责“像素矩阵”级别的读写、裁剪、重采样、位深转换、通道合并,不做大地测量;
  2. 是否能把“RPC 几何校正”与“ Pillow 图像处理”无缝衔接,形成一条可落地的 Python 流水线;
  3. 是否熟悉国产卫星(GF、ZY、HJ)常见的 RPC 文件格式(.rpc、_rpc.txt、DIM.xml)以及国内测绘局对 GeoTIFF 的元数据强制要求(CGCS2000、高斯投影、TIF Tag 34264 等)。
    一句话:用 Pillow 做“像素搬运工”,用 GDAL/Rasterio 做“坐标系搬运工”,两者通过内存数组(NumPy)握手,最后写出符合中国测绘规范的 GeoTIFF。

知识点

  1. RPC 模型原理:有理多项式系数(Ratio Polynomial Coefficients)将像方坐标 (s, l) 与物方坐标 (X, Y, Z) 建立 20 阶多项式映射,无需内外方位元素即可做严格几何校正。
  2. 国内卫星 RPC 文件字段:LINE_OFF、SAMP_OFF、LAT_OFF、LONG_OFF、HEIGHT_OFF、LINE_SCALE、SAMP_SCALE、LAT_SCALE、LONG_SCALE、HEIGHT_SCALE 以及 80 个多项式系数。
  3. 校正流程:
    ① 建立输出栅格网格(CGCS2000/高斯投影);
    ② 逐像素反算大地坐标→RPC 逆变换→像方坐标;
    ③ 双线性/三次卷积重采样;
    ④ 写入 GeoTIFF(TIF Tag 33550、33922、34737、42113)。
  4. Pillow 能力边界:
    • 支持大型 TIFF 分块读写(ImageFile.Parser + TILE_SIZE=512);
    • 支持 16 bit、32 bit 浮点(I;16、F 模式)与多通道(TIFF 的 SAMPLESPERPIXELS=4);
    • 支持自定义 TIFFTAGS,但无法直接写 GeoKeyDirectory(需 GDAL 后处理)。
  5. 线程安全:Pillow ≥8.3 在只读模式(Image.open(..., mode='r'))下释放 GIL,可在多线程中并行重采样。
  6. 国内合规细节:
    • 禁止写 PixelIsPoint,必须 PixelIsArea;
    • 高程基准:1985 国家高程基准;
    • 颜色空间:如需政务网共享,不得用 CMYK,必须用 Gray/RGB/多光谱。

答案

下面给出一条“能跑、能讲、能扩展”的参考实现,完全用国内开源轮子,不依赖 ENVI/ERDAS 商业软件,面试时可边写边讲思路。

# -*- coding: utf-8 -*-
"""
用 RPC 模型校正卫星影像并输出 GeoTIFF —— Pillow + Rasterio 方案
环境:Python 3.9+,pillow>=9.4.0,rasterio>=1.3.0,pyproj>=3.4,numpy>=1.23
数据示例:GF1 全色文件 GF1_PAN.tiff + GF1_PAN_rpc.txt
"""

import json, math, pathlib, numpy as np
from PIL import Image, TiffImagePlugin
import rasterio
from rasterio.transform import from_bounds
from rasterio.crs import CRS
import pyproj

# ---------- 1. 读影像 ----------
src_img = Image.open('GF1_PAN.tiff')          # Pillow 只读
src_arr = np.asarray(src_img)                 # 后续重采样用
width, height = src_img.size

# ---------- 2. 读 RPC ----------
def parse_rpc(txt_path):
    d = {}
    for line in open(txt_path, encoding='utf-8'):
        if '=' in line:
            k, v = line.split('=')
            d[k.strip()] = float(v.strip())
    return d

rpc = parse_rpc('GF1_PAN_rpc.txt')

# 构造正变换函数(物方→像方)
def rpc_forward(X, Y, Z):
    P = lambda coeffs, x, y, z: (
        coeffs[0] +
        coeffs[1]*y + coeffs[2]*x + coeffs[3]*z +
        coeffs[4]*y*x + coeffs[5]*y*z + coeffs[6]*x*z +
        coeffs[7]*y*y + coeffs[8]*x*x + coeffs[9]*z*z +
        coeffs[10]*x*y*z +
        coeffs[11]*y*y*y + coeffs[12]*y*x*x + coeffs[13]*y*z*z +
        coeffs[14]*y*y*x + coeffs[15]*x*x*x + coeffs[16]*x*z*z +
        coeffs[17]*y*y*z + coeffs[18]*x*x*z + coeffs[19]*z*z*z
    )
    # 归一化
    lat = (Y - rpc['LAT_OFF']) / rpc['LAT_SCALE']
    lon = (X - rpc['LONG_OFF']) / rpc['LONG_SCALE']
    h   = (Z - rpc['HEIGHT_OFF']) / rpc['HEIGHT_SCALE']
    # 20 个系数
    numL = np.array([rpc[f'LINE_NUM_COEFF_{i}'] for i in range(1,21)])
    denL = np.array([rpc[f'LINE_DEN_COEFF_{i}'] for i in range(1,21)])
    numS = np.array([rpc[f'SAMP_NUM_COEFF_{i}'] for i in range(1,21)])
    denS = np.array([rpc[f'SAMP_DEN_COEFF_{i}'] for i in range(1,21)])
    l = P(numL, lat, lon, h) / P(denL, lat, lon, h)
    s = P(numS, lat, lon, h) / P(denS, lat, lon, h)
    # 反归一化
    line = l * rpc['LINE_SCALE'] + rpc['LINE_OFF']
    samp = s * rpc['SAMP_SCALE'] + rpc['SAMP_OFF']
    return samp, line

# ---------- 3. 建立输出网格 ----------
dst_res = 2.0                                   # 2 m 地面分辨率
dst_crs = CRS.from_epsg(4534)                   # CGCS2000 / 3-degree Gauss-Kruger zone 38N
left, bottom, right, top = 129.0, 45.0, 129.2, 45.15  # 示例范围
dst_transform = from_bounds(left, bottom, right, top,
                            width=int((right-left)/dst_res),
                            height=int((top-bottom)/dst_res))
dst_width  = dst_transform.width
dst_height = dst_transform.height

# ---------- 4. 逐像素反算 + 重采样 ----------
# 这里用“反向校正”:对每一个输出像元,反求其在原始影像的位置
out = np.empty((dst_height, dst_width), dtype=np.float32)
proj = pyproj.Transformer.from_crs(dst_crs, 4326, always_xy=True)

for dst_y in range(dst_height):
    for dst_x in range(dst_width):
        x, y = dst_transform * (dst_x+0.5, dst_y+0.5)  # 中心坐标
        lon, lat = proj.transform(x, y)
        # 假定高程 0 m,可替换为外部 DEM
        Z = 0
        src_x, src_y = rpc_forward(lon, lat, Z)
        # 双线性插值
        x0, y0 = int(src_x), int(src_y)
        dx, dy = src_x - x0, src_y - y0
        if 0 <= x0 < width-1 and 0 <= y0 < height-1:
            v00 = src_arr[y0, x0]
            v01 = src_arr[y0, x0+1]
            v10 = src_arr[y0+1, x0]
            v11 = src_arr[y0+1, x0+1]
            out[dst_y, dst_x] = (
                (1-dx)*(1-dy)*v00 + dx*(1-dy)*v01 +
                (1-dx)*dy*v10     + dx*dy*v11
            )
        else:
            out[dst_y, dst_x] = 0

# ---------- 5. Pillow 写 GeoTIFF ----------
# 先写像素,再用 rasterio 追加地理信息
tmp_tif = 'tmp_pillow.tif'
Image.fromarray(out).save(tmp_tif, format='TIFF', compression='lzw')

with rasterio.open(tmp_tif, 'r+') as dst:
    dst.crs = dst_crs
    dst.transform = dst_transform
    dst.update_tags(AREA_OR_POINT='Area')
    # 国内强制元数据
    dst.update_tags(TIFFTAG_RESOLUTIONUNIT='1')  # 无单位
    dst.update_tags(TIFFTAG_DATETIME='2024:06:01 12:00:00')

print('已生成正射影像 ortho_rpc.tif')

面试讲解要点:

  1. Pillow 只负责“把校正后的像素矩阵写成 TIFF”,真正的坐标系、GeoKey 由 rasterio 追加;
  2. RPC 逆变换用“物方→像方”公式,现场推导 20 阶多项式显得太冗长,可直接说“已封装为函数”;
  3. 重采样用双线性,若数据 16 bit 只需把 dtype 换成 uint16,Pillow 同样支持;
  4. 国内项目必须写 CGCS2000 和高斯投影,否则测绘质检一票否决;
  5. 线程安全:若用多线程分块校正,Pillow 的只读 Image 可安全传递,但写盘环节必须加锁。

拓展思考

  1. 大场景分块:当影像 >50 GB 时,用 GDAL 的 VRT + Rasterio 的 blockxsize/blockysize 做窗口读写,Pillow 只处理内存块;如何保持块间重采样边缘无裂缝?——答:每块向外扩 16 像素重叠区,写完再裁剪。
  2. DEM 引入:国内常用 30 m ASTER GDEM 或 5 m 山域网 DEM,如何用 pyproj 做坐标转换后再插值高程?——答:先用 Transformer.transform(lon, lat)→DEM 行列→双线性插值 Z,再带入 RPC。
  3. 精度验证:测绘局要求检查 20 个平高控制点,中误差 ≤2 像素。如何用 Pillow 在影像上绘制红色十字标记并输出 8 bit JPEG 报审?——答:Image.new('RGB') + ImageDraw.Draw.line(),保存时 quality=95,dpi=300。
  4. 云原生部署:在阿里云函数计算中,层空间仅 500 MB,如何裁剪 GDAL 依赖?——答:用 manylinux 精简版 rasterio-wheel,去掉 HDF/NetCDF 驱动; Pillow 用 -C 编译 flag 关闭 tk、webp,减小 40 % 体积。
  5. 国产密码算法合规:若成果涉密,需用 SM4 加密 GeoTIFF,Pillow 无法直接写加密格式,但可用 pillow-jpegxl 插件写 JXL 后外部加密,面试可提“数据安全分层设计”思路。