1. 程式人生 > >TensorFlow學習--tensorflow影象處理--影象讀取/格式轉換1

TensorFlow學習--tensorflow影象處理--影象讀取/格式轉換1

一張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())
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

輸出:

[[[ 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]]]

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

這裡寫圖片描述