数据增强图函数中的Tensorflow随机数

问题描述 投票:2回答:1

我想使用crop_central函数,且其随机浮点在0.50-1.00之间,以进行数据增强。但是,当使用numpy.random.uniform(0.50, 1.00)并绘制图像时,裁切是恒定的。我通过使用4张图像并绘制8行进行调试,这些图像是相同的。

通常,问题可以表述如下:如何在数据集映射函数中使用随机数?

def data_augment(image, label=None, seed=2020):
    # I want a random number here for every individual image
    image = tf.image.central_crop(image, np.random.uniform(0.50, 1.00)) # random crop central
    image = tf.image.resize(image, INPUT_SHAPE) # the original image size

    return image

train_dataset = (
    tf.data.Dataset
        .from_tensor_slices((train_paths, train_labels))
        .map(decode_image, num_parallel_calls=AUTO)
        .map(data_augment, num_parallel_calls=AUTO)
        .repeat()
        .batch(4)
        .prefetch(AUTO)
    )

# Code to view the images
for idx, (imgs, _) in enumerate(train_dataset):
    show_imgs(imgs, 'image', imgs_per_row=4)
    if idx is 8:
        del imgs
        gc.collect()
        break
python tensorflow tensorflow-datasets data-augmentation
1个回答
0
投票

以前,我误读了这个问题。这是您正在寻找的答案。

我可以使用以下代码重新创建您的问题-

重现该问题的代码-裁剪图像的输出全部相同。

%tensorflow_version 2.x
import tensorflow as tf
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array, array_to_img
from matplotlib import pyplot as plt
import numpy as np
AUTOTUNE = tf.data.experimental.AUTOTUNE

# Set the sub plot parameters
f, axarr = plt.subplots(5,4,figsize=(15, 15))

# Load just 4 images of Cifar10
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
images = x_train[:4]

for i in range(4):
  axarr[0,i].title.set_text('Original Image')
  axarr[0,i].imshow(x_train[i])

def data_augment(images):
    image = tf.image.central_crop(images, np.random.uniform(0.50, 1.00)) # random crop central
    image = tf.image.resize(image, (32,32)) # the original image size
    return image

dataset = tf.data.Dataset.from_tensor_slices((images)).map(lambda x: data_augment(x)).repeat(4) 

print(dataset)

ix = 0
i = 1
count = 0

for f in dataset:
  crop_img = array_to_img(f)
  axarr[i,ix].title.set_text('Crop Image')
  axarr[i,ix].imshow(crop_img)
  ix=ix+1
  count = count + 1
  if count == 4:
    i = i + 1
    count = 0
    ix = 0

Output-第一行是原始图像。剩余的行是作物图像。

enter image description here

嗯,这非常具有挑战性,下面提供了两种解决方案-

解决方案1:使用np.random.uniformtf.py_function

  1. 使用np.random.uniform(0.50, 1.00)
  2. tf.py_function修饰功能调用-tf.py_function(data_augment, [x], [tf.float32])

解决问题的代码- 裁切输出图像现在​​不同并且不相同。

%tensorflow_version 2.x
import tensorflow as tf
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array, array_to_img
from matplotlib import pyplot as plt
import numpy as np
AUTOTUNE = tf.data.experimental.AUTOTUNE

# Set the sub plot parameters
f, axarr = plt.subplots(5,4,figsize=(15, 15))

# Load just 4 images of Cifar10
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
images = x_train[:4]

for i in range(4):
  axarr[0,i].title.set_text('Original Image')
  axarr[0,i].imshow(x_train[i])

def data_augment(images):
    image = tf.image.central_crop(images, np.random.uniform(0.50, 1.00)) # random crop central
    image = tf.image.resize(image, (32,32)) # the original image size
    return image

dataset = tf.data.Dataset.from_tensor_slices((images)).map(lambda x: tf.py_function(data_augment, [x], [tf.float32])).repeat(4)

ix = 0
i = 1
count = 0

for f in dataset:
  for l in f:
    crop_img = array_to_img(l)
    axarr[i,ix].title.set_text('Crop Image')
    axarr[i,ix].imshow(crop_img)
    ix=ix+1
    count = count + 1
    if count == 4:
      i = i + 1
      count = 0
      ix = 0

Output-第一行是原始图像。剩余的行是“裁剪图像”。

enter image description here

解决方案2:使用tf.random.uniformtf.py_function

  1. 使用tf.random.uniform(shape=(), minval=0.50, maxval=1).numpy()
  2. 仅通过使用以上选项,该代码将因为抛出错误AttributeError: 'Tensor' object has no attribute 'numpy'而无法正常工作。要解决此问题,您需要使用tf.py_function(data_augment, [x], [tf.float32])装饰您的功能。

解决问题的代码- 裁切输出图像现在​​不同并且不相同。

%tensorflow_version 2.x
import tensorflow as tf
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array, array_to_img
from matplotlib import pyplot as plt
import numpy as np
AUTOTUNE = tf.data.experimental.AUTOTUNE

# Set the sub plot parameters
f, axarr = plt.subplots(5,4,figsize=(15, 15))

# Load just 4 images of Cifar10
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
images = x_train[:4]

for i in range(4):
  axarr[0,i].title.set_text('Original Image')
  axarr[0,i].imshow(x_train[i])

def data_augment(images):
    image = tf.image.central_crop(images, tf.random.uniform(shape=(), minval=0.50, maxval=1).numpy()) # random crop central
    image = tf.image.resize(image, (32,32)) # the original image size
    return image

dataset = tf.data.Dataset.from_tensor_slices((images)).map(lambda x: tf.py_function(data_augment, [x], [tf.float32])).repeat(4)

ix = 0
i = 1
count = 0

for f in dataset:
  for l in f:
    crop_img = array_to_img(l)
    axarr[i,ix].title.set_text('Crop Image')
    axarr[i,ix].imshow(crop_img)
    ix=ix+1
    count = count + 1
    if count == 4:
      i = i + 1
      count = 0
      ix = 0

Output-第一行是原始图像。剩余的行是作物图像。

enter image description here

希望这能回答您的问题。祝您学习愉快。

© www.soinside.com 2019 - 2024. All rights reserved.