1. 程式人生 > >使用TensorFlow進行常用的影象處理-影象轉為矩陣以及影象大小調整1

使用TensorFlow進行常用的影象處理-影象轉為矩陣以及影象大小調整1

  • 影象編碼處理
    將影象轉為一個三維矩陣,並使用三維矩陣形成一個影象:
  • import tensorflow as tf
    import matplotlib.pyplot as plt
    
    # 讀取原始影象資料
    image_raw_data = tf.gfile.FastGFile("/tensorflow_google/cat.jpg", 'rb').read()
    
    with tf.Session() as sess:
        # 將jpg影象轉化為三維矩陣,若為png格式,可使用tf.image.decode_png
        img_data = tf.image.decode_jpeg(image_raw_data)
        # 輸出解碼之後的三維矩陣
    # print(img_data.eval()) # 使用plt顯示影象 # plt.imshow(img_data.eval()) # plt.show() # 將資料的型別轉化為實處方便處理 img_data = tf.image.convert_image_dtype(img_data, dtype=tf.uint8) # 將表示一張影象的三維矩陣重新按照jpeg格式編碼並存入檔案 encoded_image = tf.image.encode_jpeg(img_data) with tf.gfile.GFile("/tensorflow_google/encoded.jpeg"
    , '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
    • 影象大小調整
      將影象的大小統一,TensorFlow使用了四種不同的方法,並將它們封裝到tf.image.resize_images函式中:
      1)method = 0,使用雙線性插值法
      2)method = 1, 使用最近鄰法
      3)method = 2, 使用雙三次插值法
      4)method = 3, 使用面積插值法
      以下為使用程式碼:
    import tensorflow as tf
    
    # 讀取原始影象資料
    image_raw_data = tf.gfile.FastGFile("/tensorflow_google/cat.jpg", 'rb').read()
    
    with tf.Session() as sess:
        # 將jpg影象轉化為三維矩陣,若為png格式,可使用tf.image.decode_png
        img_data = tf.image.decode_jpeg(image_raw_data)
        img_data = tf.image.convert_image_dtype(img_data, dtype=tf.float32)
        # 通過tf.image.resize_images調整影象大小,size中為調整後的格式,method為調整影象大小的演算法
        resized = tf.image.resize_images(img_data, size=[300, 300], method=0)
    
        # 輸出調整後圖像的大小,深度沒有設定,所以是?
        print(resized.get_shape())
    
    >>(300, 300, ?)
      
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    注意:若出現以下錯誤
    TypeError: resize_images() got multiple values for argument ‘method’
    則是因為使用了舊版resize_images函式,如下:

    resized = tf.image.resize_images(img_data, 300, 300, method=0)
      
    • 1

    新版resize_images函式改為:

    resized = tf.image.resize_images(img_data, size=[300, 300], method=0)
      
    • 1
    					<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-2011a91181.css" rel="stylesheet">
                </div>