图像处理:编码解码处理
一张RGB图像可以看成一个三维的矩阵,矩阵中的每一个数表示了图像上不同位置,不同颜色的亮度。然而图像在存储时并不是直接记录
这些矩阵中的数字,而是记录经过压缩编码之后的结果。所以要将一张图象还原成一个三维矩阵。需要解码的过程。
下面的代码示范了如何tensorflow对 JPEG 格式图片的编码/解码函数:
编码
# 将图像使用JPEG的格式解码从而得到图像对应的三维矩阵。Tensorflow还提供了 tf.image.decode_png函数对png格式的图像进行编码。
# 解码之后的结果为一个张量, 在使用他的取值之前需要明确调用运行的过程。
image_data = tf.image.decode_jpeg(image_raw_data)
# Decode a JPEG-encoded image to a uint8 tensor 所以这里的 image_data 已经是一个tsnsor
解码
# 将表示一张图像的三维矩阵重新按照jpeg格式编码并存入文件中。打开这张图像就可以得到和原始图像一样的图像
encoded_image = tf.image.encode_jpeg(image_data)
实现完整过程
# matplotlib.pyplot 是一个python的画图工具。可以可视化tensorflow对图像的处理过程
import matplotlib.pyplot as plt
import tensorflow as tf
# 读取图像的原始数据
image_raw_data = tf.gfile.FastGFile('/lena.jpg', 'rb').read()
with tf.Session() as sess:
# 将图像使用JPEG的格式解码从而得到图像对应的三维矩阵。Tensorflow还提供了 tf.image.decode_png函数对png格式的图像进行编码。
# 解码之后的结果为一个张量, 在使用他的取值之前需要明确调用运行的过程。
image_data = tf.image.decode_jpeg(image_raw_data)
# Decode a JPEG-encoded image to a uint8 tensor 所以这里的 image_data 已经是一个tsnsor
""" # 解码后为三维矩阵
print(image_data.eval())
[[[229 248 246]
[235 245 246]
[241 242 247]
...
[238 242 251]
[238 242 251]
[238 242 251]]]
"""
# 使用pyplot工具可视化得到的图像
plt.imshow(image_data.eval())
plt.show()
# 将数据的类型转化为实数方便下面的样例程序对图像进行处理
img_data = tf.image.convert_image_dtype(image_data, dtype=tf.float32)
# 将表示一张图像的三维矩阵重新按照jpeg格式编码并存入文件中。打开这张图像就可以得到和原始图像一样的图像
encoded_image = tf.image.encode_jpeg(image_data)
with tf.gfile.GFile('C:/Users\Song Lesheng\Desktop\image_processing/image_arr.jpg', 'wb') as f:
f.write(encoded_image.eval())
```