TypeError: <tf.Tensor ... has type <class 'tensorflow.python.framework.ops.EagerTensor'>, but expected one of: numbers.Real

TypeError: <tf.Tensor ... has type <class 'tensorflow.python.framework.ops.EagerTensor'>, but expected one of: numbers.Real

我正在编写一个将图像保存到 TFRecord 文件的函数,以便随后使用 TensorFlow 的数据 API 进行读取。但是,在尝试创建 TFRecord 来保存它时,我收到以下错误消息:

TypeError: <tf.Tensor ...> has type <class 'tensorflow.python.framework.ops.EagerTensor'>, but expected one of: numbers.Real

用于创建 TFRecord 的函数是:

def create_tfrecord(filepath, label):
    
    image = tf.io.read_file(filepath)
    image = tf.image.decode_jpeg(image, channels=1)
    image = tf.image.convert_image_dtype(image, tf.float32)
    image = tf.image.resize(image, [299, 299])
    
    tfrecord = Example(
        features = Features(
            feature = {
                'image' : Feature(float_list=FloatList(value=[image])),
                'label' : Feature(int64_list=Int64List(value=[label]))
    })).SerializeToString()
    
    return tfrecord

如果您需要更多信息,请告诉我。

问题是 image 是一个张量,但您需要一个浮点值列表。尝试这样的事情:

import tensorflow as tf

def create_tfrecord(filepath, label):
    
    image = tf.io.read_file(filepath)
    image = tf.image.decode_jpeg(image, channels=1)
    image = tf.image.convert_image_dtype(image, tf.float32)
    image = tf.image.resize(image, [299, 299])
    
    tfrecord = tf.train.Example(
        features = tf.train.Features(
            feature = {
                'image' : tf.train.Feature(float_list=tf.train.FloatList(value=image.numpy().ravel().tolist())),
                'label' : tf.train.Feature(int64_list=tf.train.Int64List(value=[label]))
    })).SerializeToString()
    
    return tfrecord

create_tfrecord('/content/result_image.png', 1)

虚拟数据是这样创建的:

import numpy
from PIL import Image

imarray = numpy.random.rand(300,300,3) * 255
im = Image.fromarray(imarray.astype('uint8')).convert('RGB')
im.save('result_image.png')

如果你想重现这个例子。加载 tf-record 时,您只需将图像重塑为原始大小即可。