在 TensorFlow 数据管道中,如何用 tf.py_function 嵌入 Pillow?

解读

国内大厂(阿里、字节、商汤、旷视等)的 CV 训练框架普遍要求“离线解码 → 在线增强”两步走,但业务侧经常遇到以下痛点:

  1. 离线解码后的 .tfrecord 体积爆炸,存储与 IO 成为瓶颈;
  2. 线上新增数据格式(WebP、TIFF、多帧 GIF)时,TF 原生解码 tf.io.decode_image 无法识别或丢帧;
  3. 需要把私有业务水印、动态拉伸、CMYK→RGB 等 Pillow 成熟逻辑无缝搬进 tf.data,保证训练速度不降。

因此面试官想确认两点:

  • 你能否在“图外”用 Pillow 做复杂解码,再干净地回到“图内”;
  • 你是否理解 tf.py_function 的代价与规避手段,避免成为训练吞吐的短板。

知识点

  1. tf.py_function 核心机制

    • 把 Python 函数包装成 TensorFlow 算子,执行时脱离 Graph,运行在 Python 解释器,GIL 存在;
    • 输入输出只能是 Tensor,形状、dtype 需在包装时显式声明;
    • 与 tf.data 搭配时,需设置 num_parallel_calls 并配合 tf.data.AUTOTUNE,否则成为瓶颈。
  2. Pillow 与 Tensor 的零拷贝桥接

    • Pillow 打开后得到 PIL.Image,需先转成 numpy.ndarray(array = np.asarray(img)),再 tf.convert_to_tensor(array);
    • 若后续还要喂给 tf.image 系列算子,必须保证 dtype=tf.uint8、shape=(H,W,C) 且 C=3(RGB)。
  3. 形状与 batch 维度一致性

    • tf.py_function 会丢失静态形状,返回后必须紧接着调用 tensor.set_shape([None, None, 3]),否则后续 tf.image.resize 会报错。
  4. 训练/推理一致性陷阱

    • Pillow 与 TF 的 resize 插值方式不同:Pillow 默认 Image.BICUBIC,而 tf.image.resize 默认 BILINEAR;
    • 颜色归一化均值方差必须对齐,否则离线验证指标与线上效果对不上。
  5. 性能优化策略

    • 预解码尺寸:在 Pillow 侧先缩放到“短边 512”再返回,减少后续 TF 侧计算量;
    • 并行度:tf.data 的 map(num_parallel_calls=tf.data.AUTOTUNE) 与 Python 多线程无关,但可配合 prefetch(tf.data.AUTOTUNE) 掩盖 Python GIL 延迟;
    • 若图片极大,使用 Pillow 的 ImageFile.MAXBLOCK 调大缓冲区并开启 LOAD_TRUNCATED_IMAGES,防止解码异常导致训练中断。

答案

import tensorflow as tf
from PIL import Image
import numpy as np
import io

def pillow_decode(path_tensor, target_size=(224, 224)):
    """
    由 tf.py_function 调用的纯 Python 函数
    :param path_tensor: tf.string 标量,图片路径
    :return: tf.uint8 张量,shape=(H,W,3)
    """
    # 1. 张量 → Python bytes
    path = path_tensor.numpy().decode('utf-8')

    # 2. Pillow 打开并处理
    with Image.open(path) as im:
        # 统一颜色空间
        if im.mode != 'RGB':
            im = im.convert('RGB')
        # 可选:业务侧保持长宽比缩放到短边 256
        im.thumbnail((256, 256), Image.LANCZOS)
        # 中心裁剪到目标尺寸
        w, h = im.size
        left = (w - target_size[0]) // 2
        top = (h - target_size[1]) // 2
        im = im.crop((left, top, left + target_size[0], top + target_size[1]))

        # 3. PIL → numpy → Tensor
        np_img = np.asarray(im, dtype=np.uint8)   # shape=(224,224,3)
    return tf.convert_to_tensor(np_img, dtype=tf.uint8)

def decode_with_pillow(path_tensor):
    """
    包装成 tf.py_function 的对外接口
    """
    # 重点:指定 Tout 与 shape,否则图构建阶段无法推断
    img = tf.py_function(
        func=pillow_decode,
        inp=[path_tensor],
        Tout=tf.uint8
    )
    img.set_shape([224, 224, 3])   # 必须恢复静态形状
    return img

# 典型 tf.data 使用方式
def build_dataset(txt_path, batch=32):
    ds = tf.data.Dataset.list_files(txt_path)
    ds = ds.map(lambda p: decode_with_pillow(p),
                num_parallel_calls=tf.data.AUTOTUNE)
    ds = ds.batch(batch)
    ds = ds.prefetch(tf.data.AUTOTUNE)
    return ds

关键步骤回顾:

  1. tf.py_function 的 Tout 必须与返回张量 dtype 一致;
  2. 返回后立即 set_shape,否则后续层无法推断;
  3. 所有 Pillow 操作放在 Python 函数内,避免在图内混用;
  4. 线上推理时,务必用同一套 Pillow 预处理脚本,保证训练-推理一致性。

拓展思考

  1. 如果图片已经以二进制形式保存在 tfrecord,如何省掉磁盘 IO?
    把 bytes 特征读出来后,直接传给 Pillow:
    im = Image.open(io.BytesIO(bytes_tensor.numpy()))
    这样无需二次落盘,但注意 tf.py_function 的输入改为 bytes 而非路径。

  2. 当数据量达到单日亿级,Python GIL 成为瓶颈,如何彻底摆脱 tf.py_function?

    • 方案 A:用 TensorFlow IO 的 tfio.experimental.image.decode_tiff/webp 等扩展算子,把 Pillow 逻辑改写成 C++ 自定义算子,重新编译 TF;
    • 方案 B:离线用 Pillow 批量解码并存储为 TFRecord + tf.uint8 raw,训练阶段仅用 TF 原生算子做增强,彻底避免 Python 回调;
    • 方案 C:使用 tf.data.service + 多进程 Worker,把 py_function 分散到远端 CPU 节点,主训练器保持 GPU 满负荷。
  3. 多帧 GIF/PSD 场景下,如何只抽关键帧?
    在 Pillow 侧通过 Image.seek(frame) 与 tell() 遍历,业务规则(首帧、中间帧、随机帧)抽帧后返回,避免把整个动画读入内存;同时把帧索引作为附加张量返回,供后续网络使用。

  4. 安全与合规
    国内对“用户上传图片”要求做敏感信息过滤。可在同一 py_function 里先调用 Pillow 的 im.getexif() 读取 GPS、设备信息,剔除敏感元数据后再返回张量,满足《个人信息保护法》合规审计要求。

掌握以上要点,即可在面试中展示出“不仅能把 Pillow 塞进 TF,还知道为什么、代价多大、如何兜底”,从而拿到图像基础架构方向的高分评价。