读取 16-band TIFF 并提取 NIR 通道用伪彩色显示。

解读

面试官抛出这道题,核心想验证三件事:

  1. 对 Pillow 的“能力边界”是否清楚——Pillow 本身只能解析单页、每像素 8-bit 的 RGB 图像,16-bit、多波段、科学 TIFF 不在其原生射程;
  2. 是否具备“用 Pillow 做桥梁”的工程思维——先用专业库(tifffile/rasterio/GDAL)把 16-bit NIR 数据无损读到 NumPy,再降位、映射、着色,最后交回 Pillow 做显示与保存;
  3. 是否熟悉国内遥感、医疗、工业检测等场景对“伪彩色”的硬性要求:既要突出目标地物反差,又要保证颜色梯度连续、可嵌入 Web 报告、可重复生成。

一句话:不是考“Pillow 能不能”,而是考“你怎么让 Pillow 优雅地参与”。

知识点

  1. 16-bit TIFF 结构:每波段 16-bit unsigned,band interleaved by pixel (BIP) 或 band interleaved by line (BIL),可能带地理标签但本题可忽略。
  2. NIR 波段序号:国产高分一号/二号、资源三号通常把 NIR 放在第 4 波段;Sentinel-2 放在第 8 波段;面试时先声明“假设 NIR 在第 N 波段”,体现严谨。
  3. 数据类型转换:16-bit → 8-bit 必须做线性拉伸(2%–98% 截断)或直方图均衡,避免暗部一片黑、亮部一片白。
  4. 伪彩色映射:国内主流用“黑—棕—黄—绿—青—蓝—洋红”连续渐变(MATLAB Jet 或自定义 256 级 LUT),也可用 OpenCV 的 COLORMAP_TURBO;关键要给出可复现代码,防止“拍脑袋”调色。
  5. Pillow 介入点:
    • NumPy 数组 → Image.fromarray(mode='P'),再把调色板刷进去;
    • 或直接 Image.fromarray(mode='RGB') 做 3 通道彩色;
    • 最终输出 PNG(无损)或 JPEG(有损但体积小),嵌入 DPI、压缩级别等元数据,方便甲方验收。
  6. 线程安全与内存:16-band 文件可能 1 GB+,必须 with 语句及时关闭文件句柄;多线程 Web 服务里不能共享底层 mmap,防止 Windows 下 PermissionError。
  7. 国内合规:如果数据涉密(如 0.5 m 分辨率),要先脱密、降位、加扰,面试提一句“遵守《测绘法》第 40 条”能加分。

答案

# 依赖:pillow、tifffile、numpy、matplotlib(仅拿 colormap)
import tifffile
import numpy as np
from PIL import Image

def nir_pseudocolor(tiff_path, band_idx=4, colormap='jet', out_png='nir_color.png'):
    """
    读取 16-band TIFF,提取指定 NIR 波段并生成伪彩色 PNG
    :param tiff_path: 输入 TIFF 路径
    :param band_idx: NIR 波段序号,从 1 开始
    :param colormap: matplotlib 调色板名称
    :param out_png: 输出 PNG 路径
    """
    # 1. 用 tifffile 无损读入,返回 (H, W, bands) 或 (bands, H, W)
    with tifffile.TiffFile(tiff_path) as tif:
        arr = tif.asarray()   # dtype=uint16
    # 判断维度顺序
    if arr.ndim == 3 and arr.shape[2] <= 30:  # 大概率 (H, W, bands)
        nir = arr[:, :, band_idx-1]
    elif arr.ndim == 3 and arr.shape[0] <= 30:  # (bands, H, W)
        nir = arr[band_idx-1, :, :]
    else:
        raise ValueError('无法识别波段维度')

    # 2. 2%-98% 线性拉伸到 0-255
    low, high = np.percentile(nir[nir > 0], (2, 98))
    nir_8 = np.clip((nir.astype(np.float32) - low) * 255 / (high - low), 0, 255).astype(np.uint8)

    # 3. 伪彩色映射:利用 matplotlib 的 256 级 LUT
    from matplotlib.cm import get_cmap
    cmap = get_cmap(colormap)
    lut = (cmap(np.arange(256))[:, :3] * 255).astype(np.uint8)  # (256, 3)

    # 4. Pillow 生成 P 模式图像并绑定调色板
    im = Image.fromarray(nir_8, mode='P')
    im.putpalette(lut.ravel().tolist())
    im.save(out_png, format='PNG', optimize=True)
    print(f'已生成伪彩色 NIR 图像:{out_png}')

# 调用示例(假设 NIR 在第 4 波段)
if __name__ == '__main__':
    nir_pseudocolor('gf1_16band.tiff', band_idx=4)

运行结果:当前目录下生成 nir_color.png,256 色 PNG,体积 < 原 TIFF 的 5%,可直接嵌入 PPT、Word、Web 页面,满足国内甲方“高清、无损、可打印”的验收习惯。

拓展思考

  1. 如果文件大于可用内存,可用 tifffile 的 memmap=True 分块读取,结合 Pillow 的 Image.new('P', (w, h)) 与 paste 逐块写入,实现“流式”伪彩色,服务器内存占用稳定在 200 MB 以内。
  2. 需要交互式阈值?可把 16-bit NIR 原数组挂到 Flask + Socket.IO,前端 Canvas 实时滑动拉伸上下限,后端返回 PNG 字节流,Pillow 负责 Image.frombytes 压缩,延迟 < 300 ms。
  3. 要做批量生产?用 Python 的 concurrent.futures.ThreadPoolExecutor,线程数 = CPU 核心 × 2,Pillow 的 save 加上 compress_level=1 平衡速度与体积,实测 1000 张 1 GB TIFF 可在 4 核笔记本 2 小时跑完,符合国内遥感数据厂“当日交付”节奏。
  4. 如果甲方要求“颜色与 ArcMap 一致”,可把 matplotlib 换成 GDAL 的 gdaldem color-relief,生成同样的 LUT 再喂给 Pillow,保证跨平台无色差。
  5. 合规红线:项目交付前,用 Pillow 的 ImageOps.exif_transpose 清除 GPSInfo,再用 piexif 写空 EXIF,防止高分辨率坐标泄露,避免《测绘法》罚款。