python - 如何使用 Tensorflow 2.0 数据集在训练时执行 10 次裁剪图像增强

标签 python tensorflow tensorflow-datasets tensorflow2.0 data-augmentation

我正在使用 Tensorflow Dataset API 并从 TFRecord 文件中读取数据。我可以使用 map 函数并使用 random_flip_left_right、random_crop 等方法进行数据扩充。

但是,当我尝试复制 AlexNet 论文时,我遇到了一个问题。我需要翻转每张图片,然后进行 5 次裁剪(左、上、下、右和中)。

因此输入数据集大小将增加 10 倍。有没有办法使用 tensorflow 数据集 API 来做到这一点? map() 函数只返回一张图像,我无法增加图像的数量。

请看我现在的代码。

dataset = dataset.map(parse_image, num_parallel_calls=tf.data.experimental.AUTOTUNE) \
    .map(lambda image, label: (tf.image.random_flip_left_right(image), label), num_parallel_calls=tf.data.experimental.AUTOTUNE) \
    .map(lambda image, label: (tf.image.random_crop(image, size=[227, 227, 3]), label), num_parallel_calls=tf.data.experimental.AUTOTUNE) \
    .shuffle(buffer_size=1000) \
    .repeat() \
    .batch(256) \
    .prefetch(tf.data.experimental.AUTOTUNE)

最佳答案

def tile_crop(img, label):
    img_shape = tf.shape(img)
    crop_left = lambda img: tf.image.random_crop(img[:,:img_shape[1]//2,:], size=[227,227,3])
    crop_top = lambda img: tf.image.random_crop(img[:img_shape[0]//2,:,:], size=[227,227,3])
    ...
    img = tf.image.random_flip_left_right(img)
    img = tf.stack([crop_left(img), crop_top(img),...], axis=0])
    label = tf.reshape(label, [1,1]) #size: (,) -> (1,1)
    label = tf.tile(label, [5, 1]) #size: (1,1) -> (5,1)
    return img, label
dt = parsed_dataset.map(tile_crop) #size: ((5,height,width,channels), (5, 1))
dt = dt.unbatch() #size: ((height,width,channels), (1))

然后您可以随意使用 shuffle/repeat/batch/prefetch。确保每张裁剪后的图片都具有相同的大小。

关于python - 如何使用 Tensorflow 2.0 数据集在训练时执行 10 次裁剪图像增强,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57721797/

相关文章:

python - 在 XCode 4 中运行 PyObjC 模板时发生泄漏

python - TensorFLow:tf.contrib.rnn 模块对象不可调用

tensorflow - 使用 tf.data 在 Tensorflow-2.0 中读取图像和掩码(用于分割问题)

python - 将 .tfrecords 文件拆分为多个 .tfrecords 文件

python - 如何按特定值过滤 tf.data.Dataset?

python - 在类中使用装饰器

python - 可以重复使用 Python 内置函数的名称吗?

python - 使用 Python 代码覆盖工具理解和修剪大型库的回溯源代码

python - `order` 参数在 `tf.keras.utils.normalize()` 中意味着什么?

tensorflow - 卷积神经网络 (CNN) 输入形状