cnn之将原始图像转换成矩阵

#-*- coding:utf-8 -*-
import matplotlib.pyplot as plt
import tensorflow as tf
# 读取图像数据
img = tf.gfile.FastGFile('./images/u=605243693,3035272260&fm=26&gp=0.jpg','rb').read()

with tf.Session() as sess:
    # 用ipeg格式将图像解码得到三维矩阵(png格式用decode_png)
    # 解码后得到结果为张量
    img_data = tf.image.decode_jpeg(img)#jpeg jpg
    #img_data = tf.image.decode_png(img)
    print(img_data.eval().shape )
    print(type(img_data.eval()))
    # 打印出得到的三维矩阵
    print(img_data.eval())    # 使用pyplot可视化得到的图像
    plt.imshow(img_data.eval())
    plt.show()

    #转换格式   
    # 转换图像的数据类型
    img_data = tf.image.convert_image_dtype(img_data, dtype=tf.uint8)
    # 将图像的三维矩阵重新按照png格式存入文件
    encoded_image = tf.image.encode_png(img_data)
    # 得到图像的png格式
    with tf.gfile.GFile('model.png', 'wb') as f:
        f.write(encoded_image.eval())

输出结果:

 

本质原理: 
一张RGB格式的彩色图像可以看成是一个三维矩阵,矩阵中的每一个数代表图像不同的位置上不同的颜色的亮度.但是图像存储时并不是直接存储这些三维矩阵,而是要先对其进行压缩编码再存储.因此读取图像的过程其实是先读取其压缩编码后的结果,然后将其解码的过程

猜你喜欢

转载自blog.csdn.net/ningyanggege/article/details/86605681
今日推荐