imgaug 0.4.0 边界框增强解耦:BoundingBox 坐标 API 与 `_augment_bounding_boxes` 定制机制详解
imgaug 0.4.0 边界框增强解耦:BoundingBox 坐标 API 与 _augment_bounding_boxes 定制机制详解
本篇指南围绕 imgaug 0.4.0 引入的「Unwrapped Bounding Box Augmentation」特性展开,系统讲解 BoundingBox/Keypoint/Polygon 新增的 coords 坐标接口与 almost_equals 近似相等判定体系、四种 OnImage 容器的 items 属性,以及将边界框增强从「keypoint 包装器」中解耦出来的 _augment_bounding_boxes 定制机制。阅读完本文,你将掌握如何用坐标数组批量读写边界框、如何以容差方式比较增强前后标注是否一致,以及如何为 Lambda、AssertLambda、AssertShape 和自定义增强器精确控制边界框的增强行为,并了解该版本引入的全部兼容性影响。
背景:为什么要把边界框增强「解包」
在 0.4.0 之前,imgaug 对 BoundingBoxesOnImage 的增强是一种「包装式」(wrapper)实现:先把每个边界框的两个角点转成 keypoint,调用 keypoint 增强逻辑,再把增强后的角点组装回边界框。这种方式的问题在于,增强器无法针对边界框的特殊几何约束(例如保持角点顺序、避免框翻转、裁剪到图像边界)做单独处理,所有边界框都被迫复用 keypoint 的变换路径。
本次变更(对应 issue #446 与 #599,记录于 changelogs/0.4.0/added/20190927_unwrapped_bb_aug.md)做了三件事:
- 为
BoundingBox、Keypoint、Polygon等标注对象补齐统一的坐标数组接口和近似相等比较接口; - 为四种
OnImage容器补齐统一的items访问接口; - 引入内部方法
_augment_bounding_boxes(),让每个增强器可以独立决定边界框如何被增强,并在Lambda、AssertLambda、AssertShape上开放对应的边界框参数。
下面逐层展开。
坐标数组接口:coords 属性
0.4.0 为三种基础标注对象新增了 coords 属性,统一以 numpy.ndarray 暴露坐标,便于与 numpy/shapely 生态直接衔接。
BoundingBox.coords
BoundingBox 的 coords 属性返回一个 (2, 2) 的 float32 数组,第一行是左上角 (x1, y1),第二行是右下角 (x2, y2),实现位于 imgaug/augmentables/bbs.py:
import imgaug as ia
bb = ia.BoundingBox(x1=10, y1=20, x2=30, y2=40)
print(bb.coords)
# [[10. 20.]
# [30. 40.]]
print(bb.coords.dtype) # float32
BoundingBox 构造时会对 x1 > x2 或 y1 > y2 的输入自动交换,保证 coords 输出的两行始终是「左上」与「右下」(见 bbs.py),所以从源码结构看,coords 的返回语义是稳定可靠的。
Keypoint.coords 与 Polygon.coords
Keypoint.coords返回(1, 2)的float32数组(imgaug/augmentables/kps.py),同时Keypoint.xy直接返回coords[0, :],即(2,)的坐标对。Polygon.coords是Polygon.exterior的别名,返回(N, 2)的float32数组,N为外环顶点数(imgaug/augmentables/polys.py)。注意Polygon构造时会自动去掉与首点重合的末点,因此coords不会出现「闭合重复点」。
kp = ia.Keypoint(x=5, y=7)
print(kp.coords) # [[5. 7.]]
poly = ia.Polygon([(0, 0), (10, 0), (10, 10), (0, 10)])
print(poly.coords.shape) # (4, 2),即 exterior 的别名
容器统一接口:items
KeypointsOnImage、BoundingBoxesOnImage、PolygonsOnImage、LineStringsOnImage 四种容器同步新增了 items 属性,返回容器内持有的标注对象列表。以 BoundingBoxesOnImage 为例(imgaug/augmentables/bbs.py):
from imgaug.augmentables.bbs import BoundingBoxesOnImage
bbsoi = BoundingBoxesOnImage(
[ia.BoundingBox(y1=10, x1=20, y2=30, x2=40),
ia.BoundingBox(y1=15, x1=25, y2=35, x2=45)],
shape=(40, 50, 3))
print(bbsoi.items) # [BoundingBox(...), BoundingBox(...)]
该属性同时提供 setter(@items.setter),可整体替换容器内对象。它的意义在于:过去各容器分别暴露 keypoints/bounding_boxes/polygons/line_strings 等不同名字的属性,现在统一的 items 让泛型代码可以无差别遍历四种标注类型,这也是下文 assert_cbaois_equal 断言工具得以用同一套逻辑处理四类对象的前提。对应测试见 test/augmentables/test_bbs.py。
近似相等判定体系:coords_almost_equals 与 almost_equals
0.4.0 为 BoundingBox、Keypoint、Polygon 引入了「带容差」的相等比较接口,解决增强前后浮点坐标因插值、旋转等操作产生微小偏差而无法用 == 直接比较的问题。
BoundingBox:坐标比较与「坐标 + 标签」比较
BoundingBox.coords_almost_equals(other, max_distance=1e-4) 判断两个边界框的四个角点坐标是否近似一致(imgaug/augmentables/bbs.py):
other可以是BoundingBox实例、(2,2)/(4,)形式的ndarray,或任何可展平的迭代器;- 判定方式是对展平后的 4 个坐标值调用
np.allclose(..., atol=max_distance, rtol=0),即逐坐标绝对误差不超过max_distance; max_distance默认1e-4,语义是「欧氏距离上限」,数值越小要求越严格。
bb1 = ia.BoundingBox(x1=1, y1=3, x2=5, y2=9)
bb2 = ia.BoundingBox(x1=1, y1=3, x2=5, y2=9 + 1e-5)
print(bb1.coords_almost_equals(bb2)) # True(偏差 1e-5 < 1e-4)
print(bb1.coords_almost_equals(bb2, max_distance=1e-6)) # False
# 也支持直接传坐标数组
print(bb1.coords_almost_equals([[1, 3], [5, 9]])) # True
BoundingBox.almost_equals(other, max_distance=1e-4) 则在坐标比较之外额外比较 label:只要 self.label != other.label 就立即返回 False,否则委托给 coords_almost_equals(bbs.py)。测试覆盖了坐标相等、坐标不等、误差低于/高于阈值、数组输入、标签不同等场景(test/augmentables/test_bbs.py)。
Keypoint:almost_equals 与 coords_almost_equals 等价
Keypoint.coords_almost_equals(other, max_distance=1e-4) 对 (x, y) 坐标做同样的 np.allclose 判定,other 同样支持 Keypoint、数组与可迭代对象(imgaug/augmentables/kps.py)。Keypoint.almost_equals 目前与 coords_almost_equals 完全一致,源码注释明确说明「出于与 BoundingBox、Polygon 接口一致性而存在」(kps.py)。对应测试见 test/augmentables/test_kps.py。
Polygon:基于边采样插值的近似比较
Polygon.coords_almost_equals(other, max_distance=1e-4, points_per_edge=8) 是 Polygon.exterior_almost_equals 的别名(imgaug/augmentables/polys.py),后者是三者中最复杂的实现(polys.py):
- 允许两个多边形外环的顶点数不同;
- 判定标准是「在一个外环上随机取点,都应落在另一个外环的最近点附近」,通过把两个外环转成闭合
LineString,每条边上插值points_per_edge个点(默认 8)后逐点比较; - 源码明确提示这是一种近似测试:理论上存在「形状差异较大但被判为相等」的极端多边形,
points_per_edge越大误判概率越低,但计算量也越大; other支持Polygon、(N,2)的float32数组或(x,y)元组列表。
poly_a = ia.Polygon([(0, 0), (10, 0), (10, 10), (0, 10)])
poly_b = ia.Polygon([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]) # 顶点数不同
print(poly_a.coords_almost_equals(poly_b)) # True(顶点数差异不影响判定)
同时,Polygon.almost_equals 的行为发生了破坏性变更:不再校验 other 的数据类型,默认假定传入的就是 Polygon。也就是说,此前传入 ndarray 或列表还能被隐式接受/拒绝的用法不再可靠,调用方必须保证传入 Polygon 实例,否则以源码当前的断言逻辑会直接抛出断言错误(polys.py 附近)。
测试断言工具:assert_cbaois_equal
配合上述比较接口,imgaug.testutils 新增了 assert_cbaois_equal(observed, expected, max_distance=1e-4)(imgaug/testutils.py),用于在测试中断言「标注容器批次」是否一致:
- 若输入是
list,则逐元素递归比较,并要求两侧同为list且长度相等; - 否则要求
observed与expected类型完全一致、items数量一致、shape一致; - 对每个元素调用
coords_almost_equals做容差比较; - 特别地,当预期对象是
PolygonsOnImage时,还会校验多边形合法性:预期多边形有效则观测多边形也必须有效。
from imgaug.testutils import assert_cbaois_equal
assert_cbaois_equal(bbsoi_aug, bbsoi_expected)
这个工具被大量用于 test/augmentables/* 与 test/augmenters/* 的回归测试,是 0.4.0 验证「增强前后标注一致性」的标准断言。
解耦边界框增强:_augment_bounding_boxes 机制
这是本次变更的核心工程改进:为 Augmenter 增加内部钩子方法 _augment_bounding_boxes(bounding_boxes_on_images, random_state, parents, hooks),使每个增强器可以独立实现边界框的增强策略,而不再强制走 keypoint 包装路径。
公开入口:augment_bounding_boxes 与新增 parents 参数
公开方法 Augmenter.augment_bounding_boxes(bounding_boxes_on_images, parents=None, hooks=None)(imgaug/augmenters/meta.py)内部将输入包装为 UnnormalizedBatch(bounding_boxes=...) 后走统一批处理管线,返回 bounding_boxes_aug。
破坏性变更:该方法新增了 parents 参数,位于 hooks 之前。如果此前调用方把 hooks 作为位置参数传入(例如 augment_bounding_boxes(bbois, hooks_obj)),新签名会把它解析成 parents 从而产生错误行为——必须改为关键字传参 hooks=hooks_obj。
一个关键使用约束是:图片与边界框必须使用同一随机状态。官方 docstring 给出的标准做法是先将增强器转为 deterministic 状态(meta.py):
import numpy as np
import imgaug.augmenters as iaa
from imgaug.augmentables.bbs import BoundingBox, BoundingBoxesOnImage
A = B = C = np.ones((10, 10), dtype=np.uint8)
Abb = Bbb = Cbb = BoundingBoxesOnImage([BoundingBox(1, 1, 9, 9)], (10, 10))
seq = iaa.Fliplr(0.5)
seq_det = seq.to_deterministic()
imgs_aug = seq_det.augment_images([A, B, C])
bbs_aug = seq_det.augment_bounding_boxes([Abb, Bbb, Cbb])
否则图片与边界框会各自采样不同的随机值,导致「图片旋转 30°、边界框却旋转 -10°」的错位。每一批新数据都要重新 to_deterministic(),否则所有批次都会得到完全相同的增强。更方便的替代是使用 Augmenter.augment(),它内部自动对齐随机状态。
内部钩子与默认的 keypoint 回退
基类 Augmenter._augment_bounding_boxes(meta.py)是内部实现,默认委托给 _augment_cbaois_as_keypoints,即把每个边界框的角点当作 keypoint 增强后重组——这就是旧行为的保留路径,供未覆写的增强器向后兼容。而 _augment_bounding_boxes_as_keypoints(meta.py)显式实现了「角点转 keypoint → 调用 _augment_keypoints → 重组边界框」的转换逻辑。
docstring 还注明:这套 _augment_* 系列接口「主要为遗留支持而存在」,0.4.0 之后自定义增强的首选方式是覆写 _augment_batch。但从源码结构看,_augment_bounding_boxes 仍是各类增强器定制边界框行为的最小覆写点。
各增强器的独立实现
已有若干增强器开始覆写 _augment_bounding_boxes,证明解耦机制已落地:
Affine等几何增强器将边界框增强转发给_augment_bounding_boxes_as_keypoints(imgaug/augmenters/geometric.py),复用其内部基于skimage.transform的矩阵变换逻辑;- 池化类增强器则提供了
_augment_bounding_boxes_by_samples专用采样路径(imgaug/augmenters/pooling.py),说明不同增强器可以拥有完全不同的边界框策略。
自定义增强器的最小示例:
import imgaug.augmenters as iaa
from imgaug.augmenters import meta
from imgaug.augmentables.bbs import BoundingBoxesOnImage
class ShiftBBs(meta.Augmenter):
def _augment_bounding_boxes(self, bounding_boxes_on_images,
random_state, parents, hooks):
# 每个边界框向右下各平移 1 像素
for bboi in bounding_boxes_on_images:
for bb in bboi.items:
bb.x1 += 1; bb.y1 += 1
bb.x2 += 1; bb.y2 += 1
return bounding_boxes_on_images
def _augment_images(self, images, random_state, parents, hooks):
return images # 不修改图像,仅演示
注意:基类约定 _augment_bounding_boxes 允许原地修改容器,无需自行处理随机状态与确定性,这些由传入的 random_state 负责。
元增强器的边界框支持:Lambda、AssertLambda、AssertShape
解耦机制同步开放到了三个「元增强器」上,使自定义回调与断言也能精确控制边界框。
Lambda 新增 func_bounding_boxes
Lambda 新增参数 func_bounding_boxes,默认值为字符串 "keypoints"(imgaug/augmenters/meta.py)。取值语义(meta.py):
| 取值 | 行为 |
|---|---|
"keypoints"(默认) |
边界框角点转成 keypoint,复用 func_keypoints 逻辑 |
None |
边界框保持不变 |
callable |
以 function(bounding_boxes_on_images, random_state, parents, hooks) 形式调用,返回增强后的容器 |
def shift_bbs(bounding_boxes_on_images, random_state, parents, hooks):
for bboi in bounding_boxes_on_images:
for bb in bboi.items:
bb.x1 += 2; bb.x2 += 2
return bounding_boxes_on_images
aug = iaa.Lambda(
func_images=lambda images, random_state, parents, hooks: images,
func_bounding_boxes=shift_bbs, # 覆写默认 "keypoints"
)
从实现(meta.py)可见,回调返回后 Lambda 还会自动修正边界框的角点顺序(x1 > x2 或 y1 > y2 时交换),并断言返回值必须是可迭代的 BoundingBoxesOnImage 列表,因此回调无需担心产生「翻转后的负宽高框」。兼容性提示:func_bounding_boxes 插在构造参数序列中间,若此前用位置参数构造 Lambda,参数顺序会受影响,需改用关键字传参。
对应测试位于 test/augmenters/test_meta.py,覆盖了默认 keypoint 回退与自定义回调两条路径。
AssertLambda 新增 func_bounding_boxes
AssertLambda 同样新增 func_bounding_boxes(默认 None),回调签名相同,但要求返回 True/False 来校验边界框输入是否满足前提条件(meta.py),失败时抛出断言错误。测试用例见 test_meta.py 的 _func_bounding_boxes_succeeds/_fails 场景。
AssertShape 新增 check_bounding_boxes
AssertShape 新增布尔参数 check_bounding_boxes(默认 True,meta.py),启用后会校验(a)每张图上的边界框数量、(b)每个 BoundingBoxesOnImage.shape 是否与 AssertShape 给定的 shape 匹配:
seq = iaa.Sequential([
iaa.AssertShape((None, 32, 32, 3), check_bounding_boxes=True),
iaa.Fliplr(0.5),
])
该参数同样属于rarely breaking 变更:依赖构造参数位置顺序的调用方式需要改为关键字传参(构造签名见 meta.py)。
兼容性影响汇总与迁移建议
将本次变更涉及的破坏性影响集中整理如下:
| 变更 | 影响级别 | 迁移方式 |
|---|---|---|
Augmenter.augment_bounding_boxes 新增 parents 参数 |
breaking | 若 hooks 曾以位置参数传入,改为 hooks=... 关键字传参 |
Polygon.almost_equals 不再校验入参类型 |
breaking | 调用方保证传入 Polygon 实例 |
Lambda 新增 func_bounding_boxes |
rarely breaking | 若依赖位置参数顺序构造,改用关键字传参 |
AssertLambda 新增 func_bounding_boxes |
rarely breaking | 同上 |
AssertShape 新增 check_bounding_boxes |
rarely breaking | 同上 |
其余新增项(coords、items、coords_almost_equals、almost_equals、assert_cbaois_equal、_augment_bounding_boxes)均为纯增量,不影响既有代码。
对于 0.4.0 版本的升级,建议按以下顺序自查:
- 全局搜索
augment_bounding_boxes(的位置参数调用,确认hooks是否按关键字传入; - 检查
Polygon.almost_equals的调用点,确认实参均为Polygon; - 将手写的「增强前后标注比较」循环替换为
coords_almost_equals/assert_cbaois_equal,获得统一的容差语义; - 若自定义了增强器且需要特殊边界框几何处理,覆写
_augment_bounding_boxes而非继续依赖 keypoint 包装。
以上全部实现细节均可在当前仓库源码中直接验证:标注对象实现在 imgaug/augmentables/bbs.py、imgaug/augmentables/kps.py、imgaug/augmentables/polys.py;增强器管线实现在 imgaug/augmenters/meta.py;测试佐证见 test/augmentables/test_bbs.py、test/augmentables/test_kps.py 与 test/augmenters/test_meta.py。