TensorFlow学习--tensorflow图像处理--图像读取/格式转换

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

读取图像&转换格式

#!/usr/bin/python
# coding:utf-8

import matplotlib.pyplot as plt
import tensorflow as tf
# 读取图像数据
img = tf.gfile.FastGFile('daibola.jpg').read()

with tf.Session() as sess:
    # 用ipeg格式将图像解码得到三维矩阵(png格式用decode_png)
    # 解码后得到结果为张量
    img_data = tf.image.decode_jpeg(img)
    # 打印出得到的三维矩阵
    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/model.png', 'wb') as f:
        f.write(encoded_image.eval())

输出:

[[[ 19  18  16]
  [ 20  19  17]
  [ 22  21  19]
  ..., 
  [ 22  21  19]
  [ 22  21  19]
  [ 22  21  19]]

 [[  8   7   5]
  [ 10   9   7]
  [ 11  10   8]
  ..., 
  [  8   7   5]
  [  9   8   6]
  [ 10   9   7]]

 [[ 14  13  11]
  [ 15  14  12]
  [ 17  16  14]
  ..., 
  [ 13  12  10]
  [ 13  12  10]
  [ 15  14  12]]

 ..., 
 [[109  88  57]
  [109  88  57]
  [109  88  57]
  ..., 
  [ 35  28  18]
  [ 35  28  18]
  [ 34  27  17]]

 [[109  88  57]
  [109  88  57]
  [109  88  57]
  ..., 
  [ 34  27  17]
  [ 34  27  17]
  [ 34  27  17]]

 [[107  88  56]
  [107  88  56]
  [107  88  56]
  ..., 
  [ 32  28  17]
  [ 33  29  18]
  [ 33  29  18]]]

这里写图片描述

  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值