gpt4 book ai didi

python - 用于图像增强的 TF 数据集 API

转载 作者:行者123 更新时间:2023-11-30 22:05:21 25 4
gpt4 key购买 nike

我正在使用 tf Dataset API 来读取图像及其标签。我喜欢对图像进行多次图像增强并增加训练数据大小。我现在所做的如下。

def flip(self, img, lbl):
image = tf.image.flip_left_right(img)
return image, lbl

def transpose(self, img, lbl):
image = tf.image.transpose_image(img)
return image, lbl

# just read and resize the image.
process_fn = lambda img, lbl: self.read_convert_image(img, lbl, self.args)
flip_fn = lambda img, lbl: self.flip(img,lbl)
transpose_fn = lambda img, lbl: self.transpose(img,lbl)

train_set = self.train_set.repeat()
train_set = train_set.shuffle(args.batch_size)
train_set = train_set.map(process_fn)

fliped_data = train_set.map(flip_fn)
transpose_data = train_set.map(transpose_fn)

train_set = train_set.concatenate(fliped_data)
train_set = train_set.concatenate(transpose_data)

train_set = train_set.batch(args.batch_size)
iterator = train_set.make_one_shot_iterator()

images, labels = iterator.get_next()

有没有更好的方法来进行多重增强。上述方法的问题是,如果我添加更多的增强函数,则需要许多映射和连接。

谢谢

最佳答案

如果您想自己进行增强,而不依赖 Keras 的 ImageDataGenerator,您可以创建一个类似 img_aug 的函数,然后在您的模型或数据集 API 管道中使用它。下面的代码只是一个伪代码,但它展示了这个想法。您定义所有转换,然后您有一些通用阈值,高于该阈值您可以应用转换并尝试应用它们最多 X 次(在下面的代码中为 4)

def img_aug(image):
image = distorted_image

def h_flip():
return tf.image.flip_left_right(distorted_image)
def v_flip():
return tf.image.flip_up_down(distorted_image)

threshold = tf.constant(0.9, dtype=tf.float32)

def body(i, distorted_image):
p_order = tf.random_uniform(shape=[2], minval=0., maxval=1., dtype=tf.float32)
distorted_image = tf.case({
tf.greater(p_order[0], threshold): h_flip,
tf.greater(p_order[1], threshold): v_flip,
}
,default=identity, exclusive=False)
return (i+1, distorted_image)

def cond(i, *args):
return i < 4 # max number of transformations

parallel_iterations = 1
tf.while_loop(cond, body, [0,distorted_image],
parallel_iterations=parallel_iterations)
return distorted_image

关于python - 用于图像增强的 TF 数据集 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53044066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com