您的位置:首页 > 其它

Tensorflow图像编码处理

2017-12-29 17:02 267 查看
# Tensorflow处理图像时,将图像视为矩阵,然而图像在存储时并不直接记录这些矩阵中的数字,而是记录经过压缩编码后的结果。
# 所以要将一张图片还原成一个三维矩阵,需要解码的过程。TF提供了对jpeg和png格式图像的编码/解码函数。
# 在读入图像时,要使用解码函数才能得到三维矩阵;在保存图像时,需要使用编码函数才能将三维矩阵转换为需要的编码格式。    
import matplotlib.pyplot as plt
import tensorflow as tf
#读入图像的原始数据
image_raw_data = tf.gfile.FastGFile("F:/input.jpeg", 'rb').read()
with tf.Session() as sess:
    #将图像使用jpeg的格式解码从而得到图像对应的三维矩阵,解码之后的结果为一个张量
    img_data = tf.image.decode_jpeg(image_raw_data)
    #输出解码之后的三维矩阵
    #print (img_data.eval())
    #使用pyplot工具可视化得到的图像
    plt.imshow(img_data.eval())
    plt.show()
    #将数据的类型转换为8位无符号整型
    img_data = tf.image.convert_image_dtype(img_data, dtype=tf.uint8)
    #将表示一张图片的三维矩阵重新按照png格式编码并存入文件中。
    #在资源管理器中打开这张图像,可以得到和原始图像一样的图像
    encoder_png_image = tf.image.encode_png(img_data)
    with tf.gfile.GFile("F:/output.png", 'wb') as f:
        f.write(encoder_png_image.eval())
    
    encoder_jpeg_image = tf.image.encode_png(img_data)
    with tf.gfile.GFile("F:/output.jpeg", 'wb') as f:
        f.write(encoder_jpeg_image.eval())

如下为在Jupyter中编码的记录:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: