【问题标题】:Read Image and Mask (for segmentation problem) in Tensorflow-2.0 using tf.data使用 tf.data 在 Tensorflow-2.0 中读取图像和掩码(用于分割问题)
【发布时间】:2020-05-20 15:58:55
【问题描述】:

我正在尝试通过this 链接读取分割问题(​​1 类)的图像数据集。我的主文件夹包含两个文件夹,即 (a) img (b) maskimg 包含图像样本,mask 包含相应的掩码。我的方法是,生成图像的路径,然后更改字符串路径(即 img->mask)。我修改了here 提供的代码,现在看起来如下:

def process_path(file_path):
  file_path_str = str(file_path)
  file_path_mask = file_path_str.replace('img', 'mask') 
  # load the raw data from the file as a string
  img = tf.io.read_file(file_path)
  img = decode_img(img)

  mask = tf.io.read_file(str(file_path_mask))
  mask = decode_mask(mask)
  return img, mask

但是,当我尝试使用以下方法查看样本大小时:

for image, mask in labeled_ds.take(1):
  print("Image shape: ", image.numpy().shape)
  print("Mask shape: ", mask.numpy().shape)

我收到以下错误:

InvalidArgumentError: NewRandomAccessFile failed to Create/Open: Tensor("arg0:0", shape=(), dtype=string) : The filename, directory name, or volume label syntax is incorrect. ; Unknown error [[{{node ReadFile_1}}]] [Op:IteratorGetNextSync]

问题:关于如何从给定文件夹中读取图像和掩码而不会出现上述错误的任何建议?

【问题讨论】:

    标签: tensorflow tensorflow-datasets


    【解决方案1】:

    我们可以使用tf.regex.replace 来重命名字符串。因此,代替 python 字符串替换,使用:file_path_mask = tf.regex_replace(file_path, "img", "mask")。对于 TF 2.0,请使用 tf.strings.regex_replace

    【讨论】:

      【解决方案2】:

      类似问题的替代解决方法。我有 200 个(nb_of_images = 200)灰度图像(512、512)加载为np.array,还有 200 个二进制掩码(512、512)并加载为np.array。在for 循环中,我获取所有图像,将它们转换为EagerTensor(使用tf.convert_to_tensor),通过dtype 参数将它们转换为tf.float32,添加一维:

      img = img[:, :, tf.newaxis]
      

      所以我的图像现在是 EagerTensors 的形状 (512, 512, 1),最后我将它们附加到一个名为 images 的外部列表中。

      在同一个循环中,我对掩码执行完全相同的操作,最后将它们附加到一个名为 masks 的外部列表中。

      for 循环完成后,我基本上有两个 EagerTensors 列表,分别是

      len(images) == len(masks) == nb_of_images

      最后,我将这两个列表重新转换为 tf.Tensor:

      images_tf = tf.convert_to_tensor(images)  # convert list back to tf.Tensor
      masks_tf = tf.convert_to_tensor(masks)  # convert list back to tf.Tensor
      

      最后我创建了tf.data.Dataset

      dataset = tf.data.Dataset.from_tensor_slices((images_tf, masks_tf))  # create tf.data.Dataset
      

      【讨论】:

        猜你喜欢
        • 2019-10-24
        • 2021-03-08
        • 2019-03-25
        • 2020-06-14
        • 1970-01-01
        • 1970-01-01
        • 2016-07-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多