在大部分圖像識別問題中,通過圖像數據預處理可以儘量避免模型收到無關因素的印象或者達到數據增強的目的,從而提高模型的準確性。其中,TensorFlow就提供了一些圖像處理函數,來幫助對圖像進行處理。下面我們簡單介紹一些。
圖像編解碼處理
我們在電腦看到的彩色圖片,雖然是三個維度,即RGB,但是圖像存儲並沒有直接記錄這些信息,而是通過壓縮編的方式存儲,如jpg編碼等。要對圖片三維數據處理,則需要解碼。
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
#讀取原始圖像
image=tf.gfile.FastGFile('.\mnist_data\horse.jpg','rb').read()
with tf.Session() as sess:
img_after_decode=tf.image.decode_jpeg(image)
print(img_after_decode.eval())
plt.imshow(img_after_decode.eval())
plt.show()
我們的原始圖片如下,這是一幅我在新疆獨庫公路上拍攝的草原駿馬的圖片,手抖有點模糊。
圖像翻轉
對圖像進行翻轉可以很好增加圖像的多樣化,可以提升訓練模型的泛化能力。翻轉方式有上下翻轉,左右翻轉,隨機翻轉等。
我們看一個左右翻轉的例子,可以看到駿馬掉頭了。
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
image=tf.gfile.FastGFile('.\mnist_data\horse.jpg','rb').read()
with tf.Session() as sess:
img_after_decode=tf.image.decode_jpeg(image)
print(img_after_decode.eval())
flipped=tf.image.random_flip_left_right(img_after_decode)
plt.imshow(flipped.eval())
plt.show()
圖像色彩調整
調整圖像的色彩包括對圖像的亮度、對比度、飽和度和色相進行調整。包括固定調整和隨機調整等。現在看一個亮度調整如下:
adjusted_brightness=tf.image.random_brightness(img_after_decode,max_delta=0.9)
plt.imshow(adjusted_brightness.eval())
plt.show()
色彩調整的其他方法有
adjusted_contrast=tf.image.random_contrast(img_after_decode,0.2,18,) #對比度調整
adjusted_hue=tf.image.adjust_hue(img_after_decode,0.9) #色相調整
adjusted_saturation=tf.image.adjust_saturation(img_after_decode,6) #飽和度調整
圖像標準化
圖像標準化是將圖像的亮度均值變爲0,方差變爲1.
adjusted_stand=tf.image.per_image_standardization(img_after_decode)
圖像大小調整
resized=tf.image.resize_images(img_after_decode,[300,300],method=0) #調整大小
print(resized.dtype)
resized=np.asarray(resized.eval(),dtype="uint8")
# plt.imshow(resized)
croped=tf.image.resize_image_with_crop_or_pad(img_after_decode,300,300)#調整大小
padded=tf.image.resize_image_with_crop_or_pad(img_after_decode,1500,1500)#調整大小
central_cropped=tf.image.central_crop(img_after_decode,0.4) #調整大小
圖像標註框
batched=tf.expand_dims(tf.image.convert_image_dtype(img_after_decode,tf.float32),0)
boxs=tf.constant([[[0.05,0.05,0.9,0.7],[0.2,0.3,0.5,0.5]]])
image_boxed=tf.image.draw_bounding_boxes(batched,boxs)
plt.imshow(image_boxed[0].eval())
總結
圖像增強有利地增加了圖像的多樣性,使得訓練模型有更多類型的數據可以使用,這樣,使得模型能在更廣範圍內有作用,提升了模型的泛化能力。具體使用何種圖像增強技術,這需要在具體問題中具體分析。在實踐中摸索,在摸索中進步。