首页 > 解决方案 > 操纵矩阵张量流,tf.data.dataset 的问题

问题描述

我想连接三个大小为 [1024,1024,3] 的图像以制作一个大小为 [3,1024,1024,3] 的批次。我用 TensorFlow 编写了这段代码,但它不起作用。它返回错误"InaccessibleTensorError: The tensor 'Tensor("truediv:0", shape=(1024, 1024, 3), dtype=float32)' cannot be accessed here: it is defined in another function or code block. Use return values, explicit Python locals or TensorFlow collections to access it."

def decode_img(filename):
    image = tf.ones((3,1024,1024,3),dtype=tf.dtypes.float32)
    cnt=0
    slices = []
    for fi in filename:
      bits = tf.io.read_file(fi)
      img = tf.image.decode_jpeg(bits, channels=3)
      img = tf.image.resize(img, (1024,1024))
      slices.append(tf.cast(img, tf.float32) / 255.0)
      cnt +=1

    image = tf.stack(slices)
    return image

#-----------------------
filenames = ['img1.png', 'img2.png', 'img3.png']
dataset = tf.data.Dataset.from_tensor_slices(filenames)
dataset = dataset.map(decode_img, num_parallel_calls=AUTO)

标签: tensorflow

解决方案


一般来说,tensorflow不支持item assignment。相反,生成img您想要的所有图层,然后使用tf.stack()or tf.concatenate

filename = [img1.png, img2.png, img3.png]
cnt=0
slices = []
for fi in filename:
  bits = tf.io.read_file(fi)
  img = tf.image.decode_jpeg(bits, channels=3)
  img = tf.image.resize(img, (1024,1024))
  slices.append(tf.cast(img, tf.float32) / 255.0)
  cnt +=1

image = tf.stack(slices)

推荐阅读