TensorFlow:ValueError:'images'不包含形状

24

我使用 TensorFlow 函数 tf.image.resize_images 调整图像大小,但是在代码中遇到了以下错误:

ValueError: 'images' 包含没有形状信息。

完整的代码如下:

# -*- coding: utf-8 -*-
import tensorflow as tf
file = ["./1.jpg"]
f = tf.train.string_input_producer(file)
reader = tf.WholeFileReader()
key, img = reader.read(f)

img = tf.image.decode_image(img)
# img.set_shape([218,178,3])
img = tf.image.resize_images(img, [64,64])

coord = tf.train.Coordinator()    
with tf.Session() as sess:
    tf.train.start_queue_runners(coord=coord)
    image = sess.run(img)

完整的错误信息为

Traceback (most recent call last):
  File "image_read_test.py", line 10, in <module>
    img = tf.image.resize_images(img, [64,64])
  File "C:\Python35\lib\site-packages\tensorflow\python\ops\image_ops_impl.py", line 724, in resize_images
    raise ValueError('\'images\' contains no shape.')
ValueError: 'images' contains no shape.

然后我试图修复这个问题,但只找到了这样的一种方式

# -*- coding: utf-8 -*-
    import tensorflow as tf
    file = ["./1.jpg"]
    f = tf.train.string_input_producer(file)
    reader = tf.WholeFileReader()
    key, img = reader.read(f)

    img = tf.image.decode_image(img)
    # img.set_shape([218,178])
    # img = tf.image.resize_images(img, [64,64])

    coord = tf.train.Coordinator()    
    with tf.Session() as sess:
        tf.train.start_queue_runners(coord=coord)
        image = sess.run(img)
        image = tf.image.resize_images(image, [64,64])

只有这样函数才能正常工作,但我不知道为什么?函数tf.image.resize_images只接受numpy数组作为参数吗?还是我可以找到其他方法来解决这个问题?注意:img.set_shape([218,78,3])对我无效。

4个回答

44

传递expand_animations = False作为参数很重要:

尝试:

tf.image.decode_image(img, expand_animations = False) 

为了确保你拥有一个三维形状的张量。 这个问题是由gif格式引起的,因为decode_gif返回一个4-D数组[num_frames, height, width, 3],而其他格式包括decode_bmp、decode_jpeg和decode_png返回3-D数组[height, width, num_channels]。

欲了解更多信息,请查看相关文档


36

我最近遇到了这个问题,

tf.image.decode_image() 

它没有返回具有形状的张量,但我的图像都是jpeg格式。

所以我使用了

 tf.image.decode_jpeg() 

它返回一个解决问题的形状张量。注意还有tf.image.decode_png()

在此处可以找到更多信息:Tensorflow tf.image.decode_jpeg文档


为什么TensorFlow在decode_image()中避免使用形状参数? - Swaroop
4
@alireza Akhavan在下面回答了你的问题;原因是该方法也可以读取gif文件。文档中只提到它返回一个形状,这有点令人困惑和晦涩。 - zipline86
tf.image.decode_jpeg() 已经起作用了。难道 tf.image.decode_image() 不应该自动推断出 jpeg 格式吗? - Karan Shah

8
image_string = tf.read_file(filename)
image_decoded = tf.cond(
      tf.image.is_jpeg(image_string),
      lambda: tf.image.decode_jpeg(image_string, channels=3),
      lambda: tf.image.decode_png(image_string, channels=3))

0

我直接输入原始图像数据(即我的输入形状为(batch_size,image_height,image_width,3),并且在任何时候都没有调用decode_jpeg),然后添加。

tf.config.run_functions_eagerly(True)

对我来说,将相关的Jupyter单元格返回到原位解决了问题。

我不知道我的情况下根本原因是什么,但是我怀疑生成TFRecords时使用的Tensorflow版本与用于加载模型的版本不同,这可能是问题的一部分。


使用x = layers.Lambda(lambda x: tf.ensure_shape(x, (None, None, None, 3)))(input_image)来强制调整形状也是可行的。令人困惑的是,layers.Reshape却不行,但我猜这就是TensorFlow的特点。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接