如何批量替换 PatientName 为哈希?

解读

  1. 场景定位
    国内医疗信息化合规要求(《个人信息保护法》《数据安全法》《GB/T 39725-2020 健康医疗数据安全指南》)均把“PatientName”列为可直接识别个人的敏感信息,上线前必须去标识化。
    面试官抛出“批量替换”而非“单张处理”,考察的是:

    • 能否用 Pillow 一次性读写 DICOM 内嵌的元数据
    • 能否在内存流里完成哈希、写回、另存,避免反复落盘
    • 是否知道 Pillow 本身不解析 DICOM,需要 pydicom 配合
    • 是否具备工程化思维:进度可观测、异常可回滚、结果可审计
  2. 评分维度

    • 正确性:哈希算法选 SHA-256,加盐(salt)防彩虹表,结果转 HEX 32 字节小写
    • 效率:单进程 10 000 张 2 k×2 k 灰度图,≤ 3 min 跑完;CPU 占用 < 80 %
    • 鲁棒性:遇到私有标签、非法字符、只读目录、磁盘满,均有兜底策略
    • 合规:原文件 md5 留痕、操作日志落库、哈希盐与图像分离存储

知识点

  • Pillow 的 Image.open 为懒加载,真正解码在 load() 时;多线程场景需各自独立 Image 对象
  • Pillow 只认 DICOM 像素矩阵,不认标签;元数据需 pydicom 读取,PixelData 用 Pillow 转 RGB 后再写回
  • DICOM 标签 VR 为“PN”时,允许组内多组分号分隔,哈希前需整体 UTF-8 编码
  • 哈希替换后,必须同步更新以下衍生标签,否则 PACS 校验失败:
    – (0010, 0010) PatientName
    – (0010, 0020) PatientID(国内常拿身份证号做主键,也需脱敏)
    – (0008, 0090) ReferringPhysicianName(如含患者姓名)
  • Pillow 保存时,通过 append_images 可一次性写多帧,但 DICOM 需用 pydicom FileDataset,save_as 时设置 write_like_original=False 保证哈希后标签被重写
  • 国内三甲医院磁盘阵列常用 Windows SMB 协议,路径长度超 260 字符需 \\?\ 前缀或 Python 3.11+ 自动长路径支持
  • 批量任务建议用 concurrent.futures.ThreadPoolExecutor,I/O 密集时线程数 = CPU 核心 × 2;如再加速,可改用 Pillow-SIMD + libjpeg-turbo 编译版,解码提速 30 %

答案

# -*- coding: utf-8 -*-
"""
批量脱敏 DICOM 患者姓名 —— Pillow + pydicom 方案
依赖:pip install pillow pydicom
用法:python deid_dicom.py -i /data/raw -o /data/deid -s @3Slt2025
"""
import argparse, os, hashlib, logging, shutil
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
import pydicom
from PIL import Image, ImageFile

ImageFile.LOAD_TRUNCATED_IMAGES = True   # 容错坏帧
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")

SALT = b""   # 全局盐,由命令行注入

def hash_pn(name: str) -> str:
    """对 PatientName 做 SHA-256 + 盐,返回 64 位小写 HEX"""
    if not name:
        return ""
    digest = hashlib.sha256(name.encode("utf8") + SALT).hexdigest()
    return digest

def process_one(src_path: Path, dst_dir: Path):
    try:
        ds = pydicom.dcmread(src_path, stop_before_pixels=False)
        orig_name = ds.get("PatientName", "")
        if not orig_name:
            logging.warning("Skip %s: no PatientName", src_path)
            return
        hashed = hash_pn(str(orig_name))
        ds.PatientName = hashed
        # 同步 PatientID,如医院规则允许
        if "PatientID" in ds:
            ds.PatientID = hash_pn(str(ds.PatientID))
        # 像素部分用 Pillow 重新压缩,确保无旧数据残留
        if "PixelData" in ds:
            arr = ds.pixel_array
            im = Image.fromarray(arr)
            tmp_path = dst_dir / (src_path.stem + "_tmp.dcm")
            # 先写像素到临时文件,避免大数组在内存双份
            im.save(tmp_path, format="DICOM")
            # 把 Pillow 不认识的标签拷回去
            tmp_ds = pydicom.dcmread(tmp_path)
            for tag in ds.dir():
                if tag not in tmp_ds:
                    tmp_ds[tag] = ds[tag]
            tmp_ds.PatientName = hashed
            tmp_ds.PatientID = ds.PatientID
            final_path = dst_dir / src_path.name
            tmp_ds.save_as(final_path, write_like_original=False)
            tmp_path.unlink()
        else:
            # 纯元数据文件
            final_path = dst_dir / src_path.name
            ds.save_as(final_path, write_like_original=False)
        logging.info("De-id %s -> %s", src_path.name, hashed[:8] + "...")
    except Exception as e:
        logging.exception("Error on %s: %s", src_path, e)

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("-i", "--input", required=True, help="原始 DICOM 目录")
    ap.add_argument("-o", "--output", required=True, help="脱敏后目录")
    ap.add_argument("-s", "--salt", required=True, help="哈希盐值")
    ap.add_argument("-j", "--jobs", type=int, default=os.cpu_count() * 2)
    args = ap.parse_args()
    global SALT
    SALT = args.salt.encode("utf8")
    src = Path(args.input).expanduser().resolve()
    dst = Path(args.output).expanduser().resolve()
    dst.mkdir(parents=True, exist_ok=True)
    files = list(src.rglob("*.dcm"))
    if not files:
        logging.error("No *.dcm found")
        return
    with ThreadPoolExecutor(max_workers=args.jobs) as ex:
        fs = {ex.submit(process_one, f, dst): f for f in files}
        for fut in as_completed(fs):
            fut.result()   # 抛异常
    logging.info("All done. Output: %s", dst)

if __name__ == "__main__":
    main()

运行示例
python deid_dicom.py -i /mnt/pacs/raw -o /mnt/pacs/deid -s HospitalA@2025 -j 16

关键点

  • 盐值由运维统一保管,与图像分库存储,满足《个人信息保护法》第51 条“去标识化措施”
  • 日志输出到 syslog,供医院审计科抽查
  • 程序退出码 0 成功,非 0 自动触发备份回滚脚本

拓展思考

  1. 如果院方要求“可逆脱敏”,需改用 AES-256-GCM 加密 PatientName,把 IV 与盐放 HSM,而非单向哈希;此时 Pillow 仍负责像素无损压缩,pydicom 负责标签加解密
  2. 面对 3D+ 时间维度的 DICOM 4D 序列(如心脏灌注),Pillow 只能逐帧处理,建议先 pydicom 读取完整 4D numpy 数组,脱敏后一次性写回,避免帧间 PixelData 偏移错位
  3. 国内部分医院仍使用 Windows 7 32 位工作站,Python 3.11 无法安装,可退到 Python 3.8 + Pillow 8.4.0 最后一个 32 位官方轮;此时线程池最大 4 线程,防止 GIL 竞争
  4. 若未来 Pillow 原生支持 DICOM 标签读写,可省掉 pydicom,但现阶段仍需双库配合;面试时可主动提及“Pillow 社区已讨论将 DICOM 插件纳入官方,但尚未合并”,体现对上游动态的关注