您的位置:首页 > 其它

Tensorflow学习笔记之存取图像文件

2017-06-28 14:40 225 查看
读图的时候是用 tensorflow 的函数,存图像用的 scipy.misc 的 imsave 函数。

因为在使用 tensorflow 的队列时对存图像大小的限制有疑问所以进行测试。

import tensorflow as tf
import numpy as np
import scipy.misc

#读取图像可任意大小
filenames = ['img1.png','img2.png']

filename_queue = tf.train.string_input_producer(filenames)
reader = tf.WholeFileReader()
key,value = reader.read(filename_queue)
images = tf.image.decode_png(value)

#设置图像大小
newsize = tf.convert_to_tensor([256,256])
resized = tf.image.resize_images(images, newsize)
print(resized)
#输出是Tensor("Squeeze:0", shape=(256, 256, ?), dtype=float32)
resized.set_shape([256,256,3])
print(resized)
#输出是Tensor("Squeeze:0", shape=(256, 256, 3), dtype=float32)

flipped_images = tf.image.flip_up_down(resized)
print(flipped_images)
#输出是Tensor("ReverseV2:0", shape=(256, 256, 3), dtype=float32)

with tf.Session() as sess:
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)

init = tf.global_variables_initializer()
sess.run(init)

#reimg1的类型是<class 'numpy.ndarray'>
reimg1 = flipped_images.eval()
reimg2 = flipped_images.eval()

scipy.misc.imsave('reimg1.png', reimg1)
scipy.misc.imsave('reimg2.png', reimg2)

coord.request_stop()
coord.join(threads)


读取图像有128、256、512、1024大小的,存储时也试过这些像素,可见 scipy.misc.imsave 方法可以很容易的将 numpy 数据存成图像格式,且基本没有大小限制。

还有一种方法是用 Pillow 库的 Image 类存取图像:

from PIL import Image

# 读取图像可任意大小
im = Image.open("img1.png")
# 设定图像大小
im.thumbnail([256,256])
# 存储图像数据
im.save("img1-256x256.png")
这个方法不灵活,因为存储数据必须是Image类的对象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐