TensorFlow圖像預處理完整樣例


參考書

《TensorFlow:實戰Google深度學習框架》(第2版)

以下TensorFlow程序完成了從圖像片段截取,到圖像大小調整再到圖像翻轉及色彩調整的整個圖像預處理過程。

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# coding=utf-8 

"""
@author: Li Tian
@contact: 694317828@qq.com
@software: pycharm
@file: figure_deal_test2.py
@time: 2019/1/28 11:39
@desc: 圖像預處理完整樣例
"""

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt


# 給定一張圖像,隨機調整圖像的色彩。因為調整亮度,對比度,飽和度和色相的順序會影響最后得到的結果。
# 所以可以定義多種不同的順序。具體使用哪一種順序可以在訓練數據預處理時隨機地選擇一種。
# 這樣可以進一步降低無關因素對模型的影響。
def distort_color(image, color_ordering=0):
    if color_ordering == 0:
        image = tf.image.random_brightness(image, max_delta=32. / 255.)
        image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
        image = tf.image.random_hue(image, max_delta=0.2)
        image = tf.image.random_contrast(image, lower=0.5, upper=1.5)

    elif color_ordering == 1:
        image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
        image = tf.image.random_brightness(image, max_delta=32. / 255.)
        image = tf.image.random_contrast(image, lower=0.5, upper=1.5)
        image = tf.image.random_hue(image, max_delta=0.2)

    elif color_ordering == 2:
        # 還可以定義其他的排列,但是在這里就不再一一列出了。
        # ...
        pass

    return tf.clip_by_value(image, 0.0, 1.0)


# 給定一張解碼后的圖像、目標圖像的尺寸以及圖像上的標注框,此函數可以對給出的圖像進行預處理。
# 這個函數的輸入圖像是圖像識別問題中原始的訓練圖像,而輸出則是深井網絡模型的輸入層。注意這里
# 只是處理模型的訓練數據,對於預測的數據,一般不需要使用隨機變換的步驟。。
def preprocess_for_train(image, height, width, bbox):
    # 如果沒有提供標注框,則認為整個圖像就是需要關注的部分。
    if bbox is None:
        bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4])

    # 轉換圖像張量的類型。
    if image.dtype != tf.float32:
        image = tf.image.convert_image_dtype(image, dtype=tf.float32)

    # 隨機截取圖像,減小需要關注的物體大小對圖像識別算法的影響。
    bbox_begin, bbox_size, _ = tf.image.sample_distorted_bounding_box(tf.shape(image), bounding_boxes=bbox)
    distorted_image = tf.slice(image, bbox_begin, bbox_size)

    # 將隨機截取的圖像調整為神經網絡層輸入層的大小。大小調整的算法是隨機選擇的。
    distorted_image = tf.image.resize_images(distorted_image, [height, width], method=np.random.randint(4))

    # 隨機左右翻轉圖像。
    distorted_image = tf.image.random_flip_left_right(distorted_image)

    # 使用一種隨機的順序調整圖像色彩。
    distorted_image = distort_color(distorted_image, np.random.randint(2))

    return distorted_image


image_raw_data = tf.gfile.FastGFile('F:/Python3Space/figuredata_deal/krystal.jpg', "rb").read()
with tf.Session() as sess:
    img_data = tf.image.decode_jpeg(image_raw_data)
    boxes = tf.constant([[[0.05, 0.05, 0.9, 0.7], [0.35, 0.47, 0.5, 0.56]]])

    # 開始繪圖
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 步驟一(替換sans-serif字體)
    plt.rcParams['axes.unicode_minus'] = False  # 步驟二(解決坐標軸負數的負號顯示問題)
    fig1 = plt.figure(1, (16, 9), dpi=100)

    # 運行6次獲得6種不同的圖像。
    for i in range(6):
        # 將圖像的尺寸調整為299*299.
        ax = plt.subplot(2, 3, i+1)
        ax.set_title('運行第' + str(i+1) + '次的圖像')
        result = preprocess_for_train(img_data, 299, 299, boxes)
        plt.imshow(result.eval())

    fig1.subplots_adjust(wspace=0.1)
    # plt.tight_layout()

    plt.savefig('F:/Python3Space/figuredata_deal/圖像預處理完整樣例.jpg', bbox_inches='tight')

 

 

運行結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM