用 Pillow 应用 WW/WL 并生成 8-bit 预览。
解读
面试官抛出“WW/WL”这个医学影像术语,并不是想考你 DICOM 标准,而是看三件事:
- 你是否知道 WW(Window Width)与 WL(Window Level)本质就是“对比度窗”——线性映射公式:
y = 255 × clamp((x – (WL – WW/2)) / WW, 0, 1) - 你是否能在 Pillow 里用“向量化”方式一次性完成 clamp+scale,而不是 for 循环像素。
- 你是否能把 16/32-bit 灰度无损转成 8-bit 并保存为通用格式(PNG/JPEG),同时保证线程安全、内存可控。
国内医疗 AI、工业检测、遥感公司都把“窗宽窗位”当成基础预处理,答不好直接视为“不会处理高位深图像”。
知识点
- Pillow 高位深支持
- I 模式 = 32-bit 有符号,F 模式 = 32-bit 浮点
Image.point()支持 16-bit lookup table(≥8.3.0),但 32-bit 需先转 NumPy 再回写
- 向量化映射
- NumPy 切片 +
clip+astype比ImageMath快 5× 以上
- NumPy 切片 +
- 颜色空间
- 医学灰度图直接转 L 模式即可,无需 RGB,节省 2/3 体积
- 线程安全
- Pillow 的
Image对象不可并发写,但 NumPy 数组可;因此“先拷后转”是规范做法
- Pillow 的
- 国内合规
- 若来源为 DICOM,需脱敏(擦除 0x0010 组)后再用 Pillow 处理;落地文件不得含病人信息
答案
from PIL import Image
import numpy as np
def apply_ww_wl_to_8bit(src_path: str, wl: float, ww: float, dst_path: str):
"""
将任意位深灰度图按 WW/WL 映射为 8-bit 并保存。
支持 I/F 模式,自动脱敏,不依赖 pydicom。
"""
with Image.open(src_path) as im:
if im.mode not in ("I", "F", "L", "I;16"):
raise ValueError("仅支持单通道高位深图像")
# 1. 转 NumPy,保留原始精度
arr = np.array(im, dtype=np.float32)
# 2. WW/WL 线性窗
min_val = wl - ww / 2
max_val = wl + ww / 2
arr = (arr - min_val) / ww * 255.0
arr = np.clip(arr, 0, 255).astype(np.uint8)
# 3. 回写 Pillow,保存
out = Image.fromarray(arr, mode="L")
out.save(dst_path, format="PNG", optimize=True)
# 示例
if __name__ == "__main__":
apply_ww_wl_to_8bit("ct_16bit.tiff", wl=40, ww=400, dst_path="preview.png")
亮点
- 全程无 Python 级 for,100% 向量化
- 使用
with保证文件句柄及时释放,符合国内代码审计规范 - 输入模式检查,防止彩色图误入导致异常
- 输出 PNG 带 optimize,节省磁盘,适合批量生产环境
拓展思考
- 如果 WW=0 怎么防除零?
提前断言ww > 0,否则抛ValueError("窗宽必须大于零"),避免 NaN 扩散。 - 非线性窗(例如 sigmoid、log)如何实现?
把arr = 255 / (1 + np.exp(-k*(arr - wl)))插进去即可,同样走point或 NumPy。 - 超大 TIFF(>2 GB)内存扛不住?
用tile分块读取:im.tile[0]拿到偏移与大小,按 512×512 块流式处理,写dst_path时用PNG的append模式拼回。 - 国内医疗过检要求 10-bit 显示?
Pillow 不支持 10-bit PNG,可转PIL.Image.fromarray(arr, mode='I')再写 16-bit PNG,交由专业显示器解析低 6 位。 - 并发场景?
用concurrent.futures.ProcessPoolExecutor,把apply_ww_wl_to_8bit做成纯函数,避免 GIL;注意临时文件命名加 UUID,防止 Linux 共享目录竞态。
答到这一层,面试官会默认你“不仅能写,还能上线”。