Skip to main content
 首页 » 编程设计

python之加入 string 和 tf.string 以获取路径

2024年11月24日8wayfarer

我正在使用 tensorflow.Data API 处理一个 csv 文件。 csv 中的一个特征是图像名称。为了加载图像,我需要构建一个将基本文件夹与图像名称相结合的路径。但是,由于图像名称是一个张量,而基础文件夹是一个字符串,我无法使用 os.path.join 加入它们。我在下面包含了代码。

def process_csv_data(folder_path, image_dimensions): 
    width, height, channels = image_dimensions 
    def map_function(raw_data): 
        image_path = os.path.join(folder_path,raw_data['image_name'].numpy().decode('utf-8')) 
        image = tf.io.read_file(image_path) 
        image = tf.image.decode_jpeg(image, channels=channels) 
        image = tf.image.resize(image, [width, height]) 
        image /= 255.0  # normalize to [0,1] range 
        return image 
    return map_function 

前一个函数使用如下:

    raw_csv_dataset = tf.data.experimental.make_csv_dataset( 
        csv_path, 
        batch_size=1, 
        column_names=CSV_COLUMNS, 
        shuffle=False) 
 
    dataset = raw_csv_dataset.map( 
         process_csv_data(folder_path, image_dimensions, mode), 
         num_parallel_calls=tf.data.experimental.AUTOTUNE) 

上面的代码产生了这个错误:

AttributeError: 'Tensor' object has no attribute 'numpy'

我尝试了几种方法都没有成功,比如将文件夹名称转换为张量并使用 tf.strings.join,或者将 tf.string 转换为标准python 字符串。那么,什么是正确的方法呢?

我正在使用 tensorflow 2.0

请您参考如下方法:

只需用 + 连接字符串:

image_path = folder_path + os.sep + raw_data['image_name'] 

使用os.sep如果您确实需要路径分隔符(如果它不包含在 folder_path 中)并且不想显式使用 / 或 \.