Tensorflow:类型错误:需要二进制或 unicode 字符串,得到 dtype=string>

2024-03-17

这是代码:

filename = tf.placeholder(tf.string)
image_raw_data = tf.gfile.FastGFile(filename, "rb").read()
image = tf.image.decode_jpeg(image_raw_data)

with tf.Session() as sess:
    sess.run(image, feed_dict={filename: "4.jpg"})

这是错误:

Traceback (most recent call last):
  File "C:/Users/fanpw.fnst/Desktop/ip8/test.py", line 26, in <module>
    image_raw_data = tf.gfile.FastGFile(filename, "rb").read()
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 120, in read
    self._preread_check()
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 80, in _preread_check
    compat.as_bytes(self.__name), 1024 * 512, status)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\util\compat.py", line 67, in as_bytes
    (bytes_or_text,))
TypeError: Expected binary or unicode string, got <tf.Tensor 'Placeholder:0' shape=<unknown> dtype=string>

我想知道如何转换变量filename从类型tf.string to unicode string。或者有其他方法可以解决这个问题。

任何建议将不胜感激。


该函数需要一个字符串或字节字符串,而不是张量或占位符。 您正在寻找的是 tf.io.readfile()... 这是一个数据集的示例,但它可以用作代码中 tf.gfile 的替换

#placeholder for list of filenames
filenames = tf.placeholder(tf.string)

# Using tf.data.Dataset to iterate through list filenames
dataset = tf.data.Dataset.from_tensor_slices(filenames)
# for each filename, open it.
dataset = dataset.map(
    lambda filename: (
        tf.io.read_file(filename)))

# make iterator (standard practice)
itr = dataset.make_initializable_iterator()

#used to feed new filenames into dataset
init = itr.initializer

# get the item from iterator
image_raw_data = itr.get_next()

# same as your code
image = tf.image.decode_jpeg(image_raw_data)

with tf.Session() as sess:
    # initialize the dataset
    sess.run(init,{filenames:['test_images/demo_images/image1.jpg',
                              'test_images/demo_images/image2.jpg']})

    img1 = sess.run(image)
    img2 = sess.run(image)

# lets display the images
from PIL import Image

image = Image.fromarray(img1,'RGB')
image.show()
image = Image.fromarray(img2,'RGB')
image.show()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Tensorflow:类型错误:需要二进制或 unicode 字符串,得到 dtype=string> 的相关文章

随机推荐