TensorFlow传入字符串张量时如何读取指定路径下的图像
问题复现
当前实现的图像读取函数入参为TensorFlow字符串张量filename,代码如下:
def get_image(filename): filename = filename.numpy() img = tf.io.read_file(f'images/{filename}') return img
运行时抛出错误:AttributeError: 'Tensor' object has no attribute 'numpy',尝试启用eager execution后问题未解决,需要无需转换为numpy格式的适配方案。
报错根因
该错误通常出现在函数被tf.data.Dataset.map()调用做数据预处理的场景:数据集预处理流程默认运行在TensorFlow静态图模式,此时入参filename是静态图中的符号张量,不提供.numpy()取值方法,手动开启eager execution不会改变数据集map流程的默认执行逻辑,因此该类方案无效。
推荐实现
直接使用TensorFlow原生字符串算子完成路径拼接即可,全程保持张量运算,同时兼容eager模式和静态图模式,完全不需要转换为numpy格式:
import tensorflow as tf def get_image(filename): # 执行张量级字符串拼接,无需提取Python原生字符串值 full_path = tf.strings.join(["images/", filename]) img = tf.io.read_file(full_path) # 可直接追加后续预处理逻辑,示例: # img = tf.io.decode_image(img, channels=3, expand_animations=False) # img = tf.image.resize(img, [224, 224]) return img
如果存在必须执行Python原生逻辑的特殊场景,可在调用map时用tf.py_function包裹自定义逻辑,但上述纯TensorFlow算子的方案性能更优,为首选实现方式。
内容的提问来源于stack exchange,提问作者F777
相关产品推荐
相关产品推荐

