如何将映射函数应用于tf.Tensor

问题描述 投票:1回答:1
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

打印的输出是

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个回答
0
投票

您需要从张量中提取字符串并使用适当的图像读取功能。以下是要在代码中实现此目标的步骤。

  1. 您必须用tf.py_function(get_path, [x], [tf.float32])装饰地图功能。您可以找到有关tf.py_function here的更多信息。在tf.py_function中,第一个参数是map函数的名称,第二个参数是要传递给map函数的元素,而最后一个参数是返回类型。
  2. 您可以通过使用地图功能中的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)

输出-

enter image description here

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

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