【问题标题】:how to apply map function to the tf.Tensor如何将 map 函数应用于 tf.Tensor
【发布时间】:2020-09-16 14:58:38
【问题描述】:
dataset = tf.data.Dataset.from_tensor_slices((images,boxes))
function_to_map = lambda x,y: func3(x,y)
fast_benchmark(dataset.map(function_to_map).batch(1).prefetch(tf.data.experimental.AUTOTUNE))

现在我这里是func3

def fast_benchmark(dataset, num_epochs=2):
    start_time = time.perf_counter()
    print('dataset->',dataset)
    for _ in tf.data.Dataset.range(num_epochs):
        for _,__ in dataset:
            print(_,__)
            break
            pass

print的输出是

tf.Tensor([b'/media/jake/mark-4tb3/input/datasets/pascal/VOCtrainval_11-May-2012/VOCdevkit/VOC2012/JPEGImages/2008_000008.jpg'], shape=(1,), dtype=string) <tf.RaggedTensor [[[52, 86, 470, 419], [157, 43, 288, 166]]]>

我想在 func3() 中做什么
想要将图像目录更改为真实图像并运行批处理

【问题讨论】:

    标签: python tensorflow tensorflow2.0 tensor tensorflow-datasets


    【解决方案1】:

    您需要从张量中提取字符串并使用适当的图像读取功能。下面是实现这一点的代码中要实现的步骤。

    1. 你必须用tf.py_function(get_path, [x], [tf.float32])来装饰地图功能。您可以找到有关 tf.py_function here 的更多信息。在tf.py_function 中,第一个参数是map 函数的名称,第二个参数是要传递给map 函数的元素,最后一个参数是返回类型。
    2. 您可以通过在 map 函数中使用 bytes.decode(file_path.numpy()) 来获取您的字符串部分。
    3. 使用适当的函数来加载您的图像。我们正在使用load_img

    在下面的简单程序中,我们使用tf.data.Dataset.list_files 来读取图像的路径。接下来在map 函数中,我们使用load_img 读取图像,然后使用tf.image.central_crop 函数裁剪图像的中心部分。

    代码 -

    %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
    
    def load_file_and_process(path):
        image = load_img(bytes.decode(path.numpy()), target_size=(224, 224))
        image = img_to_array(image)
        image = tf.image.central_crop(image, np.random.uniform(0.50, 1.00))
        return image
    
    train_dataset = tf.data.Dataset.list_files('/content/bird.jpg')
    train_dataset = train_dataset.map(lambda x: tf.py_function(load_file_and_process, [x], [tf.float32]))
    
    for f in train_dataset:
      for l in f:
        image = np.array(array_to_img(l))
        plt.imshow(image)
    

    输出 -

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

    【讨论】:

    • @slowmonk - 希望我们已经回答了您的问题。如果您对答案感到满意,请您接受并投票。
    猜你喜欢
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多