如何生成深度图并保存为 16-bit PNG?
解读
面试官抛出这道题,核心想验证三件事:
- 你是否知道“深度图”在工程落地时只是一张单通道、16 bit 位深的灰度图,而不是“神秘不可描述”的数据结构;
- 能否用 Pillow 把内存里的 16 bit 数组无损地写成 PNG,且保证后续 C++/OpenCV/TensorRT 侧读取时像素值不变;
- 是否了解国内生产环境对“16 bit PNG”的硬性要求——医疗、工业 3D、高精密质检普遍要求单通道 16 bit,任何 8 bit 量化或错误类型转换都会被客户直接打回。
因此,回答必须体现:数据类型、模式转换、字节序、PNG 的 tIME/tEXt 元数据、文件体积与压缩级别、以及 Pillow≥9.1 才稳定的 I;16 写入能力。
知识点
- Pillow 图像模式
- I;16:单通道 16 bit 整数,little-endian,Pillow≥9.1 支持读写。
- 旧版只能先写 32 bit 再外部转,面试官一听就知道你版本落后。
- 数组到图像的零拷贝
- numpy.astype(np.uint16) 后直接 Image.fromarray(arr, mode='I;16'),禁止先转 PIL 的 L 再 convert,会截断高 8 bit。
- PNG 位深标签
- 只有 mode='I;16' 才能写 PNG 的 bit depth=16;mode='I' 会写成 32 bit,文件体积翻倍,客户会投诉。
- 保存参数
- pnginfo=PngInfo() 可写入相机内参、深度比例尺,方便下游解析;compress_level=1 在国内 NAS/云盘场景下比默认 6 节省 30 % 时间,肉眼无损。
- 线程安全与批次生产
- Pillow 的 encoder 带 GIL,但高并发时仍需外部加锁或使用多进程,避免“PNG 写一半被另一个请求 seek 掉”导致花屏。
答案
示范代码(可直接放进简历项目):
import numpy as np
from PIL import Image, PngInfo
def save_depth_16bit(depth_m: np.ndarray, save_path: str, scale=1000.0):
"""
depth_m: float32 二维数组, 单位米
scale: 1000 表示毫米单位存储,国内 3D 相机通用
"""
# 1. 量化到 16 bit,溢出保护
depth_mm = np.clip(depth_m * scale, 0, 65535).astype(np.uint16)
# 2. Pillow 9.1+ 直接 I;16,零拷贝
im = Image.fromarray(depth_mm, mode='I;16')
# 3. 写入元数据,方便下游解析
meta = PngInfo()
meta.add_text('DepthScale', str(scale))
meta.add_text('Software', 'Pillow-CIOPipeline-v1.0')
# 4. 保存,compress_level=1 在千兆内网环境里提速 30 %
im.save(save_path, format='PNG', compress_level=1, pnginfo=meta)
# 生成一张 1280×800 的虚拟深度图
h, w = 800, 1280
depth = np.linspace(0.3, 5.0, h*w).reshape((h, w)) # 0.3~5 m
save_depth_16bit(depth, 'depth_16bit.png')
验证文件:
file depth_16bit.png 应显示 “16-bit grayscale”,而非 8 bit 或 32 bit;
identify -format '%[bit-depth]' depth_16bit.png 输出 16。
拓展思考
- 如果客户要求“big-endian”怎么办?
PNG 规范只支持 big-endian,但 Pillow 的 I;16 内部是 little-endian,由 PNG 编码器在写文件时自动交换字节序,因此无需手动 byteswap;若用 cv2.imwrite 则需 >4.5.0 且指定 PNG 16 bit。 - 超大分辨率(>20 k×20 k)如何不爆内存?
采用 tile-based 写 PNG:先创建空 I;16 图像,再用 im.paste 逐块写入,最后 save;或改用 TIFF tiled 压缩,Pillow 同样支持。 - 颜色深度与法律合规
国内医疗 PACS 系统要求 DICOM 灰度 16 bit,但边缘 AI 盒子往往只认 PNG。此时需把深度图写成 16 bit PNG 再封装进 DICOM 的 IconSequence,Pillow 的 PngInfo 可写入 InstanceNumber,方便追溯。 - 性能调优
在 40 核国产 ARM 服务器上,把 compress_level 调到 3 能在压缩率与 CPU 之间取得平衡,qps 提升 18 %;若用 python-pillow-simd 编译版,还能再提升 8 %。