在tensorflow中读取图片,首先我们就要把图片给读取出来,这里tensorflow直接给出了文件读取的接口,我们可以使用
tf.compat.v1.gfile.FastGfile('path', 'r').read()
得到。
但是tensorflow并不是直接存储图像的矩阵数据,而是经过压缩编码的结果。
所以我们得先对其进行解码,同样tensorflow提供了对不同图片格式的解码:
- jpg: tf.image.decode_jpeg()
- png: tf.image.decode_png()
import tensorflow as tf
import matplotlib.pyplot as plt
print('*' * 20)
image_raw_png = tf.compat.v1.gfile.FastGFile('G:\Picture\people\\boy.png', 'rb').read()
image_raw_jpg = tf.compat.v1.gfile.FastGFile('G:\Picture\people\girl.jpg', 'rb').read()
print('*' * 20)
with tf.compat.v1.Session() as sess:
img_data1 = tf.image.decode_jpeg(image_raw_png) #解码
img_data2 = tf.image.decode_jpeg(image_raw_jpg)
plt.figure(1)
plt.imshow(img_data1.eval())
plt.figure(2)
plt.imshow(img_data2.eval())
plt.show()
参考资料:
1、tensorflow实现对图片的读取
2、Tensorflow图像编码处理