tf.io.read_file()

介绍

tf.io.read_file()函数用于读取文件,相当于python的open()函数

常与 tf.io.decode_jpeg() 搭配使用读取图片

语法

tf.io.read_file(
    filename,
    name=None
)
参数
  • filename:Tensor类型的string 或 python字符串
  • name:名称(可选)
返回值

Tensor型string

例子

读取图片

用该方法读取图片时,返回的Tensor结果中,是字符串类型
通过numpy()方法得到其内容,是该图片的二进制数据

import tensorflow as tf

img_tensor=tf.io.read_file(r"C:\Users\mym\Desktop\数据集\1.jpg")
print(img_tensor)
print(img_tensor.dtype)
print(img_tensor.shape)

# 通过numpy()方法获取二进制数据
img_tensor.numpy()

与python代码读取图片比较

# 用python读取图片文件
with open(r"C:\Users\mym\Desktop\数据集\1.jpg","rb") as f:
    data=f.read()
print(data)

# 比较两个文件内容是否相同
print(img_tensor.numpy()==data)

执行结果是相同的

读取图片并转成numpy矩阵

通过 tf.io.decode_jpeg() 实现

import tensorflow as tf

img_tensor=tf.io.read_file(r"C:\Users\mym\Desktop\数据集\2_class\lake\lake_001.jpg")

img_data=tf.image.decode_jpeg(img_tensor,channels=3)
img_data

img_data.numpy()

原文出处:/show_1EF4VxYA51W2.html