本文介绍了Tensorflow:类型错误:预期的二进制或 unicode 字符串,得到 <tf.Tensor 'Placeholder:0' shape=<unknown>dtype=字符串>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码如下:
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
类型转换为 unicode string
.或者有其他方法可以解决这个问题.
I'm wondering how to convert variable filename
from type tf.string
to unicode string
. Or there is some other way to solve this issue.
任何建议将不胜感激.
推荐答案
该函数需要一个字符串或字节字符串,而不是张量或占位符.您正在寻找的是 tf.io.readfile()...这是一个带有数据集的示例,但它可以用作代码中 tf.gfile 的替换
The function expects a string or byte string not a tensor or placeholder.What you are looking for is tf.io.readfile()...Here is an example with a dataset, but it can be used as the replacement in your code to 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()
这篇关于Tensorflow:类型错误:预期的二进制或 unicode 字符串,得到 <tf.Tensor 'Placeholder:0' shape=<unknown>dtype=字符串>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!