一、图像编码处理
众所周知,一张RGB彩色想可以看成一个三维矩阵,矩阵中的每一个数字表示了图像上不同位置,不同颜色的亮度。但是图像在存储时不是直接记录这些距震中的数字,而是记录经过压缩编码之后的结果,因此要将一张图像还原成一个三维矩阵,需要解码。tensorflow提供了对JPEG和PNG格式图像的编码/解码函数。
下列代码解释了编码和解码的过程
import tensorflow as tf
import matplotlib.pyplot as plt
#读取原始数据,r表示UTF-8编码,rb表示非UTF-8编码
image_raw_data = tf.gfile.FastGFile('dog.jpg','rb').read()
with tf.Session() as sess:
#对图像的JPEG格式解码从而得到图像对应的三维矩阵。tensorflow还提供了tf.image.decode_png函数对png格式的图像进行解码
#解码之后的结果为一个张量,在使用它的取值之前需要明确调用运行的过程
image_data = tf.image.decode_jpeg(image_raw_data)
#输出解码之后的三维矩阵
print(image_data.eval())
#可视化图像
plt.imshow(image_data.eval())
plt.show()
#将表示一张图像的三维矩阵重新按照JPEG格式编码并存入文件中,打开这张图像,可以得到和原始图像一样的图像
encoded_image = tf.image.encode_jpeg(image_data)
with tf.gfile.GFile('F:/python-code/tensorflow_learning/dog1.jpg','wb') as f: