如何用 Pillow 生成 YOLO 的 mosaic 四图拼接?
解读
在 YOLOv4/v5/v7 等目标检测训练流程里,mosaic 是一种离线数据增强策略:一次性把 4 张训练图像随机缩放、翻转、色域扭曲后,拼成一张 2×2 的大图,再一次性送入网络。
面试官问“用 Pillow 怎么做”,核心想验证三点:
- 你是否真正读过 YOLO 源码,知道 mosaic 的“随机性”与“标签同步”两大关键点;
- 能否用 Pillow 的 API 把“读图→缩放→翻转→色域变换→拼图→写标签”完整闭环,而不是只拼图像;
- 代码是否线程安全、内存可控、可批量生产,符合工业级数据管道要求。
国内大厂 CV 组普遍把“数据增强算子”做成多进程离线流水线,Pillow 因无 GPL 污染、跨平台、支持 30+ 格式,被用作“图像基座”。如果候选人只能说出“paste 四张图”,会被直接判为“只用过 PIL 做水印”,无法进入下一轮。
知识点
- Pillow 高速解码:Image.open(..., mode='RGB') 配合 .convert('RGB') 避免 CMYK 误读;seek() 处理 TIFF/WebP 动画帧。
- 等比例缩放与黑边策略:Thumbnail 保持纵横比,YOLO 里常用“最长边缩放到 target,短边 pad 灰条”以保留小目标;Pillow 里用 ImageOps.pad() 或自己 compute 新 size 后 paste。
- 几何增强:Image.FLIP_LEFT_RIGHT、Image.ROTATE_90/180/270、Image.transpose();随机翻转必须同步到 bbox 坐标。
- 色域扭曲:HSV 空间比 RGB 更直观,Pillow 没有直接 HSV,需转到 NumPy → cv2.cvtColor 改 H、S、V → 再转回 Pillow;注意 uint8 溢出。
- 2×2 网格随机中心偏移:YOLO 源码里 cx∈[0.25w,0.75w], cy∈[0.25h,0.75h],保证四张图不会完全对称,增加小目标密度。
- 标签同步:COCO 或 YOLO txt 格式,bbox 为 cx,cy,w,h 相对坐标;拼图后需把每张图的 bbox 映射到“大图”坐标系,并做越界裁剪+面积过滤(面积<1 px 的框直接丢弃)。
- 线程安全与内存:Image.load() 会把懒加载变成 eager,防止在多进程里频繁 seek;用完及时 close(),避免 fd 泄漏。
- 批量生产:Python multiprocessing.Pool 搭配 producer-consumer,Pillow 的 GIL 只在解码/编码时释放,因此 CPU 核心数≈进程数即可,I/O 密集场景可再开大。
- 格式回写:JPEG 质量 95、optimize=True、progressive=True,减少重新压缩损失;PNG 用压缩级别 6 平衡速度与体积。
- 随机种子隔离:多进程下必须 Random(seed + worker_id),否则所有 worker 产出同分布,导致 mosaic 失效。
答案
import random, math, os, json
from PIL import Image, ImageOps, ImageEnhance
import numpy as np
import cv2
MOSAIC_SIZE = 640 # 输出大图边长
MIN_OFFSET = 0.25 # 中心随机偏移下限
MAX_OFFSET = 0.75 # 中心随机偏移上限
MIN_VIS = 0.3 # bbox 被裁后最小可见比例
def load_image(path):
img = Image.open(path).convert('RGB')
img.load() # 线程安全
return img
def random_distort_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):
im = np.array(im, dtype=np.uint8)
im = cv2.cvtColor(im, cv2.COLOR_RGB2HSV).astype(np.float32)
r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1
im[..., 0] = (im[..., 0] * r[0]) % 180
im[..., 1] = np.clip(im[..., 1] * r[1], 0, 255)
im[..., 2] = np.clip(im[..., 2] * r[2], 0, 255)
im = cv2.cvtColor(im.astype(np.uint8), cv2.COLOR_HSV2RGB)
return Image.fromarray(im)
def random_flip(im, boxes):
if random.random() < 0.5:
im = im.transpose(Image.FLIP_LEFT_RIGHT)
boxes[:, 0] = 1 - boxes[:, 0] # cx 翻转
return im, boxes
def resize_pad(im, target_long=640):
w, h = im.size
scale = target_long / max(w, h)
new_w, new_h = int(w*scale), int(h*scale)
im = im.resize((new_w, new_h), Image.LANCZOS)
# 灰条 pad 到正方形
im = ImageOps.pad(im, (target_long, target_long), color=(114,114,114))
return im, scale
def load_labels(txt_path):
# YOLO 格式: cls cx cy w h
return np.loadtxt(txt_path, ndmin=2).reshape(-1, 5)
def mosaic_four(index_list, img_dir, lbl_dir):
assert len(index_list) == 4
images, labels = [], []
for idx in index_list:
img_path = os.path.join(img_dir, f'{idx}.jpg')
lbl_path = os.path.join(lbl_dir, f'{idx}.txt')
im = load_image(img_path)
boxes = load_labels(lbl_path)
im, boxes = random_flip(im, boxes)
im = random_distort_hsv(im)
im, scale = resize_pad(im, MOSAIC_SIZE//2)
# 把 bbox 缩放到当前子图坐标系
boxes[:, 1::2] *= im.height
boxes[:, 2::2] *= im.width
images.append(im)
labels.append(boxes)
# 随机中心
cx = int(random.uniform(MIN_OFFSET, MAX_OFFSET) * MOSAIC_SIZE)
cy = int(random.uniform(MIN_OFFSET, MAX_OFFSET) * MOSAIC_SIZE)
mosaic = Image.new('RGB', (MOSAIC_SIZE, MOSAIC_SIZE), (114,114,114))
final_boxes = []
placements = [
(0, 0, cx, cy), # top-left
(cx, 0, MOSAIC_SIZE, cy), # top-right
(0, cy, cx, MOSAIC_SIZE), # bottom-left
(cx, cy, MOSAIC_SIZE, MOSAIC_SIZE)
]
for (x0, y0, x1, y1), im, lbs in zip(placements, images, labels):
sub_w, sub_h = x1-x0, y1-y0
im = im.resize((sub_w, sub_h), Image.LANCZOS)
mosaic.paste(im, (x0, y0))
# 坐标映射到大图
lbs = lbs.copy()
lbs[:, 1] += x0 # cx
lbs[:, 2] += y0 # cy
# 归一化
lbs[:, 1] /= MOSAIC_SIZE
lbs[:, 2] /= MOSAIC_SIZE
lbs[:, 3] *= im.width / MOSAIC_SIZE # w
lbs[:, 4] *= im.height / MOSAIC_SIZE # h
final_boxes.append(lbs)
final_boxes = np.vstack(final_boxes)
# 越界裁剪
x1 = np.clip(final_boxes[:, 1] - final_boxes[:, 3]/2, 0, 1)
x2 = np.clip(final_boxes[:, 1] + final_boxes[:, 3]/2, 0, 1)
y1 = np.clip(final_boxes[:, 2] - final_boxes[:, 4]/2, 0, 1)
y2 = np.clip(final_boxes[:, 2] + final_boxes[:, 4]/2, 0, 1)
final_boxes[:, 1] = (x1+x2)/2
final_boxes[:, 2] = (y1+y2)/2
final_boxes[:, 3] = x2 - x1
final_boxes[:, 4] = y2 - y1
# 面积过滤
area = final_boxes[:, 3] * final_boxes[:, 4]
keep = area > (MIN_VIS * area.max())
final_boxes = final_boxes[keep]
return mosaic, final_boxes
# 使用示例
if __name__ == '__main__':
img_dir = 'images'
lbl_dir = 'labels'
idx_pool = [x.split('.')[0] for x in os.listdir(img_dir)]
chosen = random.sample(idx_pool, 4)
mosaic_img, mosaic_lbl = mosaic_four(chosen, img_dir, lbl_dir)
mosaic_img.save('mosaic_out.jpg', quality=95, optimize=True)
np.savetxt('mosaic_out.txt', mosaic_lbl, fmt='%.6f')
代码要点
- 四张图先各自做增强、缩到 320×320 左右,再拼成 640×640;
- 中心点随机,避免网格死板;
- bbox 同步映射、归一化、越界裁剪、面积过滤,保证训练时不会引入无效框;
- Pillow 负责解码、几何、拼图,NumPy+OpenCV 负责色域,分工明确;
- 多进程场景下把
random换成np.random.RandomState(seed+worker_id)即可。
拓展思考
- 速度瓶颈:JPEG 解码占 60% 耗时,国内大厂做法是把原始图一次性解码成内存映射
.mmap或 LMDB,Pillow 直接Image.frombuffer,省去反复 I/O。 - 小目标消失:当四张图都缩到 1/4 尺寸时,原图 8×8 像素目标会变成 2×2,可能被面积过滤掉。解决方法是“混合 mosaic”:以 50% 概率只拼 2 张图,另 2 张保持原尺寸贴边角,兼顾大中小目标分布。
- 标签格式兼容:COCO JSON 需把
bbox:[x,y,w,h]转poly再裁剪,Pillow 的ImageDraw.Draw.polygon可用于可视化验证;工业上建议统一转 YOLO txt,避免双格式维护。 - 动态 shape 训练:YOLOv8 支持 640~1280 多尺度,mosaic 输出尺寸可做成随机 32 的倍数,Pillow 拼图后统一
resize((s,s)),标签同步乘比例即可。 - 合规风险:国内数据出境审查趋严,若训练图含人脸、车牌,需在 mosaic 阶段同步做“随机遮挡”或“像素化”处理,Pillow 的
ImageFilter.GaussianBlur(radius=10)可快速打码,避免后期人工返工。