用 Pillow 绘制 COCO bbox 并支持类别色板。

解读

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

  1. 你是否真的“用过” Pillow——不是背 API,而是能把 Image、ImageDraw、ImageFont 串成业务闭环;
  2. 对 COCO 数据格式是否熟:bbox=[x, y, width, height]、category_id 是整数、类别名通过 categories 映射;
  3. 工程化思维:颜色不能写死,要“可扩展、可配置、线程安全”,最好还能抗中文路径、抗高分屏字体模糊。

国内真实场景里,这道题常出现在“数据可视化工具链”或“AI 标注质检系统”岗位,面试官会追问:
“如果类别 >100 怎么保证颜色不重复?”
“如果图片 2 万像素宽,字体怎么自适应?”
“如果要在服务器批量跑,如何加速?”
因此答案必须给出“可落地的代码骨架 + 参数解释 + 性能兜底方案”。

知识点

  1. COCO bbox 坐标系:左上角原点,x/y 整数像素,width/height 非负;Pillow 的 rectangle 需要右下坐标+1,否则边框会被吃掉一个像素。
  2. 类别色板策略:
    a. 内置 CSS 16 色快速演示;
    b. >16 类用 HSV 环形采样,再转 RGB,保证视觉区分度;
    c. 提供“颜色缓存字典”避免每图重复计算。
  3. Pillow 绘图三件套:
    Image.open → ImageDraw.Draw → draw.rectangle / text;
    文字用 ImageFont.truetype,中文场景优先加载“SimHei.ttf”或“msyh.ttc”,防止 □ 乱码。
  4. 抗锯齿与线宽:rectangle 不支持线宽>1,可用 draw.line 手画四条边;或先放大 2 倍再缩小,兼顾清晰度。
  5. 批量安全:
    显式 close 文件句柄,用 with 上下文;
    多线程下 Image 对象不可共享,必须每个线程独立 open。
  6. 服务器无头环境:安装 pillow-simd 加速,字体路径用 fc-list 找系统盘,避免硬编码。

答案

# coco_draw.py
import os, json, colorsys, itertools
from PIL import Image, ImageDraw, ImageFont

class COCOVisualizer:
    def __init__(self,
                 categories_path: str,
                 font_path: str = None,
                 line_thickness: int = 2):
        """
        categories_path: COCO 的 categories.json 或整个 instances_train2017.json
        font_path: 若 None,自动找系统黑体
        """
        with open(categories_path, 'r', encoding='utf-8') as f:
            cats = json.load(f)['categories']
        self.cid2name = {c['id']: c['name'] for c in cats}
        self.cid2color = self._build_color_palette(len(self.cid2name))
        self.line_th = line_thickness
        self.font = self._get_font(font_path)

    # ---------- 公共 API ----------
    def draw_file(self, img_path, anns, out_path=None):
        """anns: COCO 格式的单张图片标注列表"""
        img = Image.open(img_path).convert('RGB')
        self._draw_anns(img, anns)
        if out_path:
            img.save(out_path, quality=95, subsampling=0)
        return img

    # ---------- 内部工具 ----------
    def _build_color_palette(self, n):
        """返回 dict: category_id -> (R,G,B)"""
        if n <= 16:
            base = ['#e6194b', '#3cb44b', '#ffe119', '#4363d8',
                    '#f58231', '#911eb4', '#46f0f0', '#f032e6',
                    '#bcf60c', '#fabebe', '#008080', '#e6beff',
                    '#9a6324', '#fffac8', '#800000', '#aaffc3']
            rgb = [tuple(int(h[i+1:i+3], 16) for i in (0,2,4)) for h in base]
            return {cid: rgb[i % len(rgb)] for i, cid in enumerate(self.cid2name.keys())}

        step = 1.0 / n
        palette = {}
        for i, cid in enumerate(self.cid2name.keys()):
            h = i * step
            s = 0.8
            v = 0.9
            r, g, b = colorsys.hsv_to_rgb(h, s, v)
            palette[cid] = tuple(int(x*255) for x in (r, g, b))
        return palette

    def _get_font(self, font_path):
        if font_path and os.path.isfile(font_path):
            return ImageFont.truetype(font_path, size=16)
        # 国内常见系统黑体
        candidates = ['C:/Windows/Fonts/simhei.ttf',   # Win
                      '/System/Library/Fonts/STHeiti Medium.ttc',  # mac
                      '/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf']  # Linux
        for c in candidates:
            if os.path.isfile(c):
                return ImageFont.truetype(c, size=16)
        return ImageFont.load_default()  # 兜底,可能无中文

    def _draw_anns(self, img, anns):
        draw = ImageDraw.Draw(img)
        for ann in anns:
            x, y, w, h = ann['bbox']
            cid = ann['category_id']
            color = self.cid2color[cid]
            # 画框
            for offset in range(self.line_th):
                draw.rectangle([x+offset, y+offset, x+w-offset-1, y+h-offset-1],
                               outline=color)
            # 写字
            text = self.cid2name[cid]
            # 简单计算文字背景
            tw, th = draw.textsize(text, font=self.font)
            draw.rectangle([x, y-th-4, x+tw+2, y], fill=color)
            draw.text((x+2, y-th-2), text, fill=(255,255,255), font=self.font)

# ----------------- 使用示例 -----------------
if __name__ == '__main__':
    viz = COCOVisualizer('instances_val2017.json')
    # 假设已通过 cocoapi 捞出某张图的所有 anns
    anns = [{'bbox': [100, 150, 200, 300], 'category_id': 1},
            {'bbox': [300, 400, 150, 200], 'category_id': 3}]
    viz.draw_file('demo.jpg', anns, out_path='demo_out.jpg')

运行后 demo_out.jpg 即可看到带类别名、颜色不重叠、中文无乱码的 COCO 风格 bbox。
若类别数 >100,把 _build_color_palette 里的 s, v 再做抖动即可进一步区分。

拓展思考

  1. 超高分图:先下采样到 4k 以内绘图,再映射坐标回原图,既省内存又避免字体过小。
  2. 批量万图:用 multiprocessing.Pool,每个进程预加载字体与色板,CPU 吃满;SSD 顺序写盘,避免 I/O 抖动。
  3. 颜色无障碍:引入 CIEDE2000 色差公式,自动过滤掉与背景色相近的边框色,提升质检员肉眼效率。
  4. 与 OpenCV 混用:Pillow 画完转成 numpy 数组,再用 cv2 画掩膜(支持透明叠加),兼顾 Pillow 的字体优势与 OpenCV 的掩膜速度。
  5. 在线服务:封装成 FastAPI,上传图片 + JSON → 返回 base64 结果图;利用 pillow-simd + uvloop,单核 QPS 可稳在 200+(2242×2242 输入)。