TensorFlow图像读取&显示
Tensorflow image reading & display
我有一堆格式类似于 Cifar10 的图像(二进制文件,每个图像 size = 96*96*3
字节),一张接一张 (STL-10 dataset)。我打开的文件有 138MB。
我尝试阅读并检查包含图像的张量的内容以确保阅读正确,但是我有两个问题 -
FixedLengthRecordReader
是否加载整个文件,但一次只提供一个输入?由于读取前 size
个字节应该相对较快。但是,代码大约需要两分钟才能 运行。
- 如何以可显示的格式获取实际图像内容,或者在内部显示它们以验证图像是否被正确读取?我做了
sess.run(uint8image)
,但是结果是空的。
代码如下:
import tensorflow as tf
def read_stl10(filename_queue):
class STL10Record(object):
pass
result = STL10Record()
result.height = 96
result.width = 96
result.depth = 3
image_bytes = result.height * result.width * result.depth
record_bytes = image_bytes
reader = tf.FixedLengthRecordReader(record_bytes=record_bytes)
result.key, value = reader.read(filename_queue)
print value
record_bytes = tf.decode_raw(value, tf.uint8)
depth_major = tf.reshape(tf.slice(record_bytes, [0], [image_bytes]),
[result.depth, result.height, result.width])
result.uint8image = tf.transpose(depth_major, [1, 2, 0])
return result
# probably a hack since I should've provided a string tensor
filename_queue = tf.train.string_input_producer(['./data/train_X'])
image = read_stl10(filename_queue)
print image.uint8image
with tf.Session() as sess:
result = sess.run(image.uint8image)
print result, type(result)
输出:
Tensor("ReaderRead:1", shape=TensorShape([]), dtype=string)
Tensor("transpose:0", shape=TensorShape([Dimension(96), Dimension(96), Dimension(3)]), dtype=uint8)
I tensorflow/core/common_runtime/local_device.cc:25] Local device intra op parallelism threads: 4
I tensorflow/core/common_runtime/local_session.cc:45] Local session inter op parallelism threads: 4
[empty line for last print]
Process finished with exit code 137
我运行在我的 CPU 上安装这个,如果有任何补充的话。
编辑:感谢 Rosa,我找到了纯 TensorFlow 解决方案。显然,当使用 string_input_producer
时,为了看到结果,您需要初始化队列 运行ners。
唯一需要添加到上面代码的是下面的第二行:
...
with tf.Session() as sess:
tf.train.start_queue_runners(sess=sess)
...
之后result
中的图像可以用matplotlib.pyplot.imshow(result)
显示。我希望这可以帮助别人。如果您还有其他问题,请随时问我或查看 Rosa 的回答中的 link。
在评论中与您交谈后,我相信您可以使用 numpy/scipy 来完成此操作。想法是读取 numpy
3d 数组中的图像并将其输入变量。
from scipy import misc
import tensorflow as tf
img = misc.imread('01.png')
print img.shape # (32, 32, 3)
img_tf = tf.Variable(img)
print img_tf.get_shape().as_list() # [32, 32, 3]
然后你可以运行你的图表:
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
im = sess.run(img_tf)
并验证是否相同:
import matplotlib.pyplot as plt
fig = plt.figure()
fig.add_subplot(1,2,1)
plt.imshow(im)
fig.add_subplot(1,2,2)
plt.imshow(img)
plt.show()
P.S. 您提到:Since it's supposed to parallelize reading, it seems useful to know.
。我可以说,在数据分析中,读取数据很少是瓶颈。您的大部分时间都将花在训练模型上。
根据documentation你可以解码JPEG/PNG张图片。
应该是这样的:
import tensorflow as tf
filenames = ['/image_dir/img.jpg']
filename_queue = tf.train.string_input_producer(filenames)
reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)
images = tf.image.decode_jpeg(value, channels=3)
您可以找到更多信息here
只是为了给出一个完整的答案:
filename_queue = tf.train.string_input_producer(['/Users/HANEL/Desktop/tf.png']) # list of files to read
reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)
my_img = tf.image.decode_png(value) # use png or jpg decoder based on your files.
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
# Start populating the filename queue.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for i in range(1): #length of your filename list
image = my_img.eval() #here is your image Tensor :)
print(image.shape)
Image.fromarray(np.asarray(image)).show()
coord.request_stop()
coord.join(threads)
或者如果你有一个图片目录,你可以通过 this Github source file
添加它们
@mttk 和@salvador-dali:我希望这是你需要的
(无法发表评论,声望不够,但这是对我有用的修改版本)
对于关于 No default session is registered
的@HamedMP 错误,您可以使用 InteractiveSession
来消除此错误:
https://www.tensorflow.org/versions/r0.8/api_docs/python/client.html#InteractiveSession
对于@NumesSanguis Image.show
的问题,您可以使用常规的 PIL .show()
方法,因为 fromarray
returns 是一个图像对象。
我在下面都做了(注意我使用的是 JPEG 而不是 PNG):
import tensorflow as tf
import numpy as np
from PIL import Image
filename_queue = tf.train.string_input_producer(['my_img.jpg']) # list of files to read
reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)
my_img = tf.image.decode_jpeg(value) # use png or jpg decoder based on your files.
init_op = tf.initialize_all_variables()
sess = tf.InteractiveSession()
with sess.as_default():
sess.run(init_op)
# Start populating the filename queue.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for i in range(1): #length of your filename list
image = my_img.eval() #here is your image Tensor :)
Image.fromarray(np.asarray(image)).show()
coord.request_stop()
coord.join(threads)
使用 tf.train.match_filenames_once 加载名称获取要使用 tf.size 迭代的文件数
打开会话并享受 ;-)
import tensorflow as tf
import numpy as np
import matplotlib;
from PIL import Image
matplotlib.use('Agg')
import matplotlib.pyplot as plt
filenames = tf.train.match_filenames_once('./images/*.jpg')
count_num_files = tf.size(filenames)
filename_queue = tf.train.string_input_producer(filenames)
reader=tf.WholeFileReader()
key,value=reader.read(filename_queue)
img = tf.image.decode_jpeg(value)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
num_files = sess.run(count_num_files)
for i in range(num_files):
image=img.eval()
print(image.shape)
Image.fromarray(np.asarray(image)).save('te.jpeg')
我使用的是 CIFAR10 格式而不是 STL10,结果代码类似
filename_queue = tf.train.string_input_producer(filenames)
read_input = read_cifar10(filename_queue)
with tf.Session() as sess:
tf.train.start_queue_runners(sess=sess)
result = sess.run(read_input.uint8image)
img = Image.fromarray(result, "RGB")
img.save('my.jpg')
该片段与 mttk 和 Rosa Gronchi 相同,但不知何故我无法在 运行 时间内显示图像,所以我保存为 JPG 文件。
您可以使用 tf.keras API.
import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing.image import load_img, array_to_img
tf.enable_eager_execution()
img = load_img("example.png")
img = tf.convert_to_tensor(np.asarray(img))
image = tf.image.resize_images(img, (800, 800))
to_img = array_to_img(image)
to_img.show()
首先,scipy.misc.imread 和 PIL 不再可用。而是使用 imageio 库,但您需要为此安装 Pillow 作为依赖项
pip install Pillow imageio
然后使用以下代码加载图像并获取有关它的详细信息。
import imageio
import tensorflow as tf
path = 'your_path_to_image' # '~/Downloads/image.png'
img = imageio.imread(path)
print(img.shape)
或
img_tf = tf.Variable(img)
print(img_tf.get_shape().as_list())
两者都很好。
我有一堆格式类似于 Cifar10 的图像(二进制文件,每个图像 size = 96*96*3
字节),一张接一张 (STL-10 dataset)。我打开的文件有 138MB。
我尝试阅读并检查包含图像的张量的内容以确保阅读正确,但是我有两个问题 -
FixedLengthRecordReader
是否加载整个文件,但一次只提供一个输入?由于读取前size
个字节应该相对较快。但是,代码大约需要两分钟才能 运行。- 如何以可显示的格式获取实际图像内容,或者在内部显示它们以验证图像是否被正确读取?我做了
sess.run(uint8image)
,但是结果是空的。
代码如下:
import tensorflow as tf
def read_stl10(filename_queue):
class STL10Record(object):
pass
result = STL10Record()
result.height = 96
result.width = 96
result.depth = 3
image_bytes = result.height * result.width * result.depth
record_bytes = image_bytes
reader = tf.FixedLengthRecordReader(record_bytes=record_bytes)
result.key, value = reader.read(filename_queue)
print value
record_bytes = tf.decode_raw(value, tf.uint8)
depth_major = tf.reshape(tf.slice(record_bytes, [0], [image_bytes]),
[result.depth, result.height, result.width])
result.uint8image = tf.transpose(depth_major, [1, 2, 0])
return result
# probably a hack since I should've provided a string tensor
filename_queue = tf.train.string_input_producer(['./data/train_X'])
image = read_stl10(filename_queue)
print image.uint8image
with tf.Session() as sess:
result = sess.run(image.uint8image)
print result, type(result)
输出:
Tensor("ReaderRead:1", shape=TensorShape([]), dtype=string)
Tensor("transpose:0", shape=TensorShape([Dimension(96), Dimension(96), Dimension(3)]), dtype=uint8)
I tensorflow/core/common_runtime/local_device.cc:25] Local device intra op parallelism threads: 4
I tensorflow/core/common_runtime/local_session.cc:45] Local session inter op parallelism threads: 4
[empty line for last print]
Process finished with exit code 137
我运行在我的 CPU 上安装这个,如果有任何补充的话。
编辑:感谢 Rosa,我找到了纯 TensorFlow 解决方案。显然,当使用 string_input_producer
时,为了看到结果,您需要初始化队列 运行ners。
唯一需要添加到上面代码的是下面的第二行:
...
with tf.Session() as sess:
tf.train.start_queue_runners(sess=sess)
...
之后result
中的图像可以用matplotlib.pyplot.imshow(result)
显示。我希望这可以帮助别人。如果您还有其他问题,请随时问我或查看 Rosa 的回答中的 link。
在评论中与您交谈后,我相信您可以使用 numpy/scipy 来完成此操作。想法是读取 numpy
3d 数组中的图像并将其输入变量。
from scipy import misc
import tensorflow as tf
img = misc.imread('01.png')
print img.shape # (32, 32, 3)
img_tf = tf.Variable(img)
print img_tf.get_shape().as_list() # [32, 32, 3]
然后你可以运行你的图表:
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
im = sess.run(img_tf)
并验证是否相同:
import matplotlib.pyplot as plt
fig = plt.figure()
fig.add_subplot(1,2,1)
plt.imshow(im)
fig.add_subplot(1,2,2)
plt.imshow(img)
plt.show()
P.S. 您提到:Since it's supposed to parallelize reading, it seems useful to know.
。我可以说,在数据分析中,读取数据很少是瓶颈。您的大部分时间都将花在训练模型上。
根据documentation你可以解码JPEG/PNG张图片。
应该是这样的:
import tensorflow as tf
filenames = ['/image_dir/img.jpg']
filename_queue = tf.train.string_input_producer(filenames)
reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)
images = tf.image.decode_jpeg(value, channels=3)
您可以找到更多信息here
只是为了给出一个完整的答案:
filename_queue = tf.train.string_input_producer(['/Users/HANEL/Desktop/tf.png']) # list of files to read
reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)
my_img = tf.image.decode_png(value) # use png or jpg decoder based on your files.
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
# Start populating the filename queue.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for i in range(1): #length of your filename list
image = my_img.eval() #here is your image Tensor :)
print(image.shape)
Image.fromarray(np.asarray(image)).show()
coord.request_stop()
coord.join(threads)
或者如果你有一个图片目录,你可以通过 this Github source file
添加它们@mttk 和@salvador-dali:我希望这是你需要的
(无法发表评论,声望不够,但这是对我有用的修改版本)
对于关于 No default session is registered
的@HamedMP 错误,您可以使用 InteractiveSession
来消除此错误:
https://www.tensorflow.org/versions/r0.8/api_docs/python/client.html#InteractiveSession
对于@NumesSanguis Image.show
的问题,您可以使用常规的 PIL .show()
方法,因为 fromarray
returns 是一个图像对象。
我在下面都做了(注意我使用的是 JPEG 而不是 PNG):
import tensorflow as tf
import numpy as np
from PIL import Image
filename_queue = tf.train.string_input_producer(['my_img.jpg']) # list of files to read
reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)
my_img = tf.image.decode_jpeg(value) # use png or jpg decoder based on your files.
init_op = tf.initialize_all_variables()
sess = tf.InteractiveSession()
with sess.as_default():
sess.run(init_op)
# Start populating the filename queue.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for i in range(1): #length of your filename list
image = my_img.eval() #here is your image Tensor :)
Image.fromarray(np.asarray(image)).show()
coord.request_stop()
coord.join(threads)
使用 tf.train.match_filenames_once 加载名称获取要使用 tf.size 迭代的文件数 打开会话并享受 ;-)
import tensorflow as tf
import numpy as np
import matplotlib;
from PIL import Image
matplotlib.use('Agg')
import matplotlib.pyplot as plt
filenames = tf.train.match_filenames_once('./images/*.jpg')
count_num_files = tf.size(filenames)
filename_queue = tf.train.string_input_producer(filenames)
reader=tf.WholeFileReader()
key,value=reader.read(filename_queue)
img = tf.image.decode_jpeg(value)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
num_files = sess.run(count_num_files)
for i in range(num_files):
image=img.eval()
print(image.shape)
Image.fromarray(np.asarray(image)).save('te.jpeg')
我使用的是 CIFAR10 格式而不是 STL10,结果代码类似
filename_queue = tf.train.string_input_producer(filenames)
read_input = read_cifar10(filename_queue)
with tf.Session() as sess:
tf.train.start_queue_runners(sess=sess)
result = sess.run(read_input.uint8image)
img = Image.fromarray(result, "RGB")
img.save('my.jpg')
该片段与 mttk 和 Rosa Gronchi 相同,但不知何故我无法在 运行 时间内显示图像,所以我保存为 JPG 文件。
您可以使用 tf.keras API.
import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing.image import load_img, array_to_img
tf.enable_eager_execution()
img = load_img("example.png")
img = tf.convert_to_tensor(np.asarray(img))
image = tf.image.resize_images(img, (800, 800))
to_img = array_to_img(image)
to_img.show()
首先,scipy.misc.imread 和 PIL 不再可用。而是使用 imageio 库,但您需要为此安装 Pillow 作为依赖项
pip install Pillow imageio
然后使用以下代码加载图像并获取有关它的详细信息。
import imageio
import tensorflow as tf
path = 'your_path_to_image' # '~/Downloads/image.png'
img = imageio.imread(path)
print(img.shape)
或
img_tf = tf.Variable(img)
print(img_tf.get_shape().as_list())
两者都很好。