You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

KerasCV增强层为何在YOLOv8训练中损坏图像标签?

解决YOLOv8图像增强后边界框标签失效问题

问题根源

  1. 数据处理顺序错误:当前先对数据集执行ragged_batch再应用增强,Keras CV增强层对批量RaggedTensor格式的bounding boxes存在兼容性问题,导致标签丢失。
  2. 类别标签类型错误:将类别标签转换为float32,而Keras CV增强层默认期望类别为整数类型,浮点类型会被内部逻辑过滤。

修复方案

1. 调整数据处理流程:先增强,再批量

将增强操作移至ragged_batch之前,确保增强层处理单个样本的bounding boxes,而非批量RaggedTensor结构。

2. 保持类别标签为整数类型

类别标签无需转换为浮点型,保留int32类型即可,避免被增强层误过滤。

修改后的核心代码

def to_tf_format(img_path, img_class, img_box):
    image = tf.io.read_file(img_path)
    image = tf.image.decode_jpeg(image, channels=3)

    print(f"img = {image}, cls = {img_class}, box = {img_box}")

    # 类别标签保持int32类型,无需转float32
    classes = tf.cast(img_class, dtype=tf.int32)
    boxes = tf.cast(img_box, dtype=tf.float32)

    bounding_boxes = {
        "classes": classes,
        "boxes": boxes,
    }

    return {"images": tf.cast(image, tf.float32), "bounding_boxes": bounding_boxes}

augmentor = keras.Sequential(
    layers=[
        keras_cv.layers.RandomFlip(mode="horizontal", bounding_box_format="rel_xyxy"),
        keras_cv.layers.RandomShear(
            x_factor=0.2, y_factor=0.2, bounding_box_format="rel_xyxy"
        ),
        keras_cv.layers.JitteredResize(
            (640, 640), scale_factor=(0.7, 1.3), bounding_box_format="rel_xyxy"
        ),
    ]
)

def dict_to_tuple(inputs):
    return inputs["images"], inputs["bounding_boxes"]

# 调整顺序:先增强,再批量
train_ds = train_data.map(to_tf_format, num_parallel_calls=tf.data.AUTOTUNE)
train_ds = train_ds.shuffle(BATCH_SIZE * 4)
train_ds = train_ds.map(augmentor, num_parallel_calls=tf.data.AUTOTUNE)  # 增强移至batch前
train_ds = train_ds.ragged_batch(BATCH_SIZE, drop_remainder=True)
train_ds = train_ds.map(dict_to_tuple, num_parallel_calls=tf.data.AUTOTUNE)
train_ds = train_ds.prefetch(tf.data.AUTOTUNE)

验证

修改后,执行next(iter(train_ds.take(1)))[1]应返回包含有效classes和boxes的RaggedTensor,增强后的边界框标签会被正确保留。

内容的提问来源于stack exchange,提问作者Jackson Thomas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 05:53:24