如何在tensorflow Tensor上使用os.path.join?

yrdbyhpb  于 2022-11-16  发布在  其他
关注(0)|答案(1)|浏览(161)

我正在尝试使用tensorflow.data.data API创建自定义Tensorflow数据集。但是,我的原始数据包含许多较小的图像(称为图块),必须将这些图块连接起来才能形成较大的图像。这些图块也在进行图像增强。因此,使用了os.path.join。但是,os.path.join不适用于TensorflowTensor。错误消息:

main_image_path = os.path.join(INDIVIDUAL_TILE_PATH, image_id)
    File "C:\ProgramData\Anaconda3\envs\3.9\lib\ntpath.py", line 117, in join  *
        genericpath._check_arg_types('join', path, *paths)
    File "C:\ProgramData\Anaconda3\envs\3.9\lib\genericpath.py", line 152, in _check_arg_types  *
        raise TypeError(f'{funcname}() argument must be str, bytes, or '

    TypeError: join() argument must be str, bytes, or os.PathLike object, not 'Tensor'

Process finished with exit code 1

显而易见的解决方案是将Tensor转换为字符串,但str(image_id)似乎不起作用。

def createDynamicDatasetFromIDsLabels(ID, labels, mode="train"):
    dataset = (
        tf.data.Dataset
            .from_tensor_slices((ID, labels))
            .map(decodeImages, num_parallel_calls=AUTO)
            #.repeat()
            #.shuffle(BATCH_SIZE * 5)
            #.batch(BATCH_SIZE)
            #.prefetch(AUTO)
    )

    return dataset

def decodeImages(image_id, label):
    main_image_path = os.path.join(INDIVIDUAL_TILE_PATH, image_id)
    tiles_list_paths = glob.glob(main_image_path + "*")

    augmentedTiles = map(DataAugmentation.data_augment, tiles_list_paths) ##DATA AUGMENT READS TILES AND AUGMENTS
    tile_list_images = list(augmentedTiles)

    concat_image = glue_to_one(tile_list_images)
    plt.imshow(concat_image)
    plt.show()

    return concat_image, label

def glue_to_one(imgs_seq):
    first_row= tf.concat((imgs_seq[0], imgs_seq[1],imgs_seq[2],imgs_seq[3]), 0)
    second_row = tf.concat((imgs_seq[4], imgs_seq[5], imgs_seq[6], imgs_seq[7]), 0)
    third_row = tf.concat((imgs_seq[8], imgs_seq[9], imgs_seq[10], imgs_seq[11]), 0)
    fourth_row = tf.concat((imgs_seq[12], imgs_seq[13], imgs_seq[14], imgs_seq[15]), 0)

    img_glue = tf.stack((first_row, second_row, third_row, fourth_row), axis=1)
    img_glue = tf.reshape(img_glue, [512,512,3])

    return img_glue```
9w11ddsr

9w11ddsr1#

您可以使用tf.strings.join代替os.path.join,并使用os.path.sep指定运算符。下面是一个小的工作示例,您可以使用tf.strings从文件路径中获取文件夹路径:

filepath = tf.convert_to_tensor('C:\ProgramData\Anaconda3\envs\3.9\lib\ntpath.py')
folderpath = tf.strings.split(filepath, os.path.sep)
folderpath = tf.strings.join(filepath[0:-1], os.path.sep)

相关问题