Tensorflow 从tfrecords解码JPEG错误:ValueError:形状必须为秩0,但对于';解码JPEG';(op:';解码JPEG';)输入形状:[?]

Tensorflow 从tfrecords解码JPEG错误:ValueError:形状必须为秩0,但对于';解码JPEG';(op:';解码JPEG';)输入形状:[?],tensorflow,tensorflow2.0,Tensorflow,Tensorflow2.0,我应用了本文中的方法将JPEG文件写入.tfrecords。但我在解析它们时遇到了问题 这是我写tfrecords的代码,每个x\u img是一个numpy数组,每个x\u img[i]包含固定数量的img\u字节 img_bytes = open(join(frames_path, vid, img_list[current]),'rb').read() ... "x_img": tf.train.Feature( bytes_list = tf.train.BytesLi

我应用了本文中的方法将JPEG文件写入.tfrecords。但我在解析它们时遇到了问题

这是我写tfrecords的代码,每个
x\u img
是一个numpy数组,每个
x\u img[i]
包含固定数量的
img\u字节

img_bytes = open(join(frames_path, vid, img_list[current]),'rb').read()
...
"x_img": tf.train.Feature( bytes_list = tf.train.BytesList( value= x_img[i])),
解析时,我执行了以下操作:

def parse_func(example_proto):

    # FEATURES
    feature_description = {
        "x_img": tf.io.VarLenFeature(tf.string),
        }
    feat = tf.io.parse_single_example(example_proto, feature_description)
        
    x = {}
    x_img = tf.sparse.to_dense(feat["x_img"])
    x_img = tf.io.decode_jpeg(x_img, channels = 3)

    x["x_img"] = x_img/255

    
    return x
但它返回错误:

ValueError: Shape must be rank 0 but is rank 1 for 'DecodeJpeg' (op: 'DecodeJpeg') with input shapes: [?].
解码以前以字节存储的JPEG的正确方法是什么?

完整答案:
tf.io.decode\u jpeg
工作正常。我得到错误的原因是我将输入整形为
(n,宽度,高度,3)
。但是函数
decode\u jpeg
只对单个图像有效,而不是n个图像

以书面形式:

x_img = tf.stack([
    tf.io.decode_jpeg(x_images[0], channels = 3),
    tf.io.decode_jpeg(x_images[1], channels = 3),
    tf.io.decode_jpeg(x_images[2], channels = 3),
])
我可以将字节恢复为JPEG格式。更有效的方法是使用列表理解,但不幸的是,现在不支持列表理解(请参阅)

将字节写入
.tfrecords
而不是使用
plt.imread()
cv2.imread()
的原因是它不会解压缩图像,因此处理速度更快,节省空间。我没有精确计算,但解压缩JPEG图像会使磁盘空间增加约6倍