TensorFlow支持JPG、PNG圖像格式,RGB、RGBA顏色空間。圖像用與圖像尺寸相同(height*width*chnanel)張量表示。通道表示為包含每個通道顏色數量標量秩1張量。圖像所有像素存在磁碟文件,需要被載入到記憶體。 圖像載入與二進位文件相同。圖像需要解碼。輸入生成器(tf.tr ...
TensorFlow支持JPG、PNG圖像格式,RGB、RGBA顏色空間。圖像用與圖像尺寸相同(height*width*chnanel)張量表示。通道表示為包含每個通道顏色數量標量秩1張量。圖像所有像素存在磁碟文件,需要被載入到記憶體。
圖像載入與二進位文件相同。圖像需要解碼。輸入生成器(tf.train.string_input_producer)找到所需文件,載入到隊列。tf.WholeFileReader載入完整圖像文件到記憶體,WholeFileReader.read讀取圖像,tf.image.decode_jpeg解碼JPEG格式圖像。圖像是三階張量。RGB值是一階張量。載入圖像格式為[batch_size,image_height,image_width,channels]。批數據圖像過大過多,占用記憶體過高,系統會停止響應。
大尺寸圖像輸入占用大量系統記憶體。訓練CNN需要大量時間,載入大文件增加更多訓練時間,也難存放多數系統GPU顯存。大尺寸圖像大量無關本征屬性信息,影響模型泛化能力。
tf.image.decode_jpeg解碼JPEG格式圖像。tf.image.decode_png解碼PNG格式圖像。 差別在alpha(透明度)信息。移除區域alpha值設0,有助於標識。JPEG圖像頻繁操作會留下偽影(atrifact)。PNG格式無損壓縮,保留原始文件全部信息(被縮放或降採樣除外),文件體積較大。
TensorFlow內置文件格式TFRecord,二進位數據和訓練類別標簽數據存儲在同一文件。模型訓練前圖像轉換為TFRecord格式。TFRecord文件是protobuf格式。數據不壓縮,可快速載入到記憶體。
獨熱編碼(one-hot encoding)格式,表示多類分類(單)標簽數據。圖像載入到記憶體,轉換為位元組數組,添加到tf.train.Example文件,SerializeToString 序列化為二進位字元,保存到磁碟。序列化將記憶體對象轉換為可安全傳輸文件格式,可被載入,可被反序列化為樣本格式。直接載入TFRecord文件,可以節省訓練時間。支持寫入多個樣本。
TFRecordReader對象讀取TFRecord文件。tf.parse_single_example不解碼圖像,解析TFRecord,圖像按原始位元組讀取(tf.decode-raw)。tf.reshape調整形狀,使佈局符合tf.nn.conv2d要求([image_height,image_width,image_channels])。tf.expand擴展維數,把batch_size維添加到input_batch。tf.equal檢查是否載入同一圖像。sess.run(tf.cast(tf_record_features['label'], tf.string))查看從TFRecord文件載入的標簽。使用圖像數據推薦使用TFRecord文件存儲數據與標簽。做好圖像預處理並保存結果。
最好在預處理階段完成圖像操作,裁剪、縮放、灰度調整等。圖像載入後,翻轉、扭曲,使輸入網路訓練信息多樣化,緩解過擬合。Python圖像處理框架PIL、OpenCV。TensorFlow提供部分圖像處理方法。裁剪,tf.image.central_crop,移除圖像區域,完全丟棄其中信息,與tf.slice(移除張量分量)類似,基於圖像中心返回結果。訓練時,如果背景有用,tf.image.crop_to_bounding_box(只接收確定形狀張量,輸入圖像需要事先在數據流圖運行) 隨機裁剪區域起始位置到圖像中心的偏移量。
tf.image.pad_to_bounding_box 用0填充邊界,使輸入圖像符合期望尺寸。尺寸過大過小圖像,邊界填充灰度值0像素。tf.image.resize_image_with_crop_or_pad,相對圖像中心,裁剪或填充同時進行。
翻轉,每個像素位置沿水平或垂真方向翻轉。隨機翻轉圖像,可以防止過擬合。tf.slice選擇圖像數據子集。tf.image.flip_left_right 完成水平翻轉。tf.image.flip_up_down 完成垂直翻轉。seed參數控制翻轉隨機性。
編輯過圖像訓練,誤導CNN模型。屬性隨機修改,使CNN精確匹配編輯過或不同光照圖像特征。tf.image.adjust_brightness 調整灰度。tf.image.adjust_contrast 調整對比度。調整對比度,選擇較小增量,避免“過曝”,達到最大值無法恢復,可能全白全黑。tf.slice 突出改變像素。tf.image.adjust_hue 調整色度,色彩更豐富。delta參數控制色度數量。tf.image.adjust_saturation 調整飽和度,突出顏色變化。
單一顏色圖像,灰度顏色空間,單顏色通道,只需要單個分量秩1張量。縮減顏色空間可以加速訓練。灰度圖具有單個分量,取值範圍[0,255]。tf.image.rgb_to_grayscale 把RGB圖像轉換為灰度圖。灰度變換,每個像素所有顏色值取平均。tf.image.rgb_to_hsv RGB圖像轉換為HSV, 色度、飽和度、灰度構成HSV顏色空間,3個分量秩1張量。更貼近人類感知屬性。HSB,B亮度值。tf.image.hsv_to_rgb HSV圖像轉換為RGB,tf.image.grayscale_to_rgb 灰度圖像轉換為RGB。python-colormath提供LAB顏色空間,顏色差異映射貼近人類感知,兩個顏色歐氏距離反映人類感受的顏色差異。
tf.image.convert_image_dtype(image, dtype,saturate=False) 圖像數據類型變化,像素值比例變化。
import tensorflow as tf sess = tf.Session() red = tf.constant([255, 0, 0]) file_names = ['./images/chapter-05-object-recognition-and-classification/working-with-images/test-input-image.jpg'] filename_queue = tf.train.string_input_producer(file_names) image_reader = tf.WholeFileReader() _, image_file = image_reader.read(filename_queue) image = tf.image.decode_jpeg(image_file) sess.run(tf.global_variables_initializer()) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess,coord=coord) print sess.run(image) filename_queue.close(cancel_pending_enqueues=True) coord.request_stop() coord.join(threads) print "------------------------------------------------------" image_label = b'\x01' image_loaded = sess.run(image) image_bytes = image_loaded.tobytes() image_height, image_width, image_channels = image_loaded.shape writer = tf.python_io.TFRecordWriter("./output/training-image.tfrecord") example = tf.train.Example(features=tf.train.Features(feature={ 'label': tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_label])), 'image': tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_bytes])) })) print example writer.write(example.SerializeToString()) writer.close() print "------------------------------------------------------" tf_record_filename_queue = tf.train.string_input_producer(["./output/training-image.tfrecord"]) tf_record_reader = tf.TFRecordReader() _, tf_record_serialized = tf_record_reader.read(tf_record_filename_queue) tf_record_features = tf.parse_single_example( tf_record_serialized, features={ 'label': tf.FixedLenFeature([], tf.string), 'image': tf.FixedLenFeature([], tf.string), }) tf_record_image = tf.decode_raw( tf_record_features['image'], tf.uint8) tf_record_image = tf.reshape( tf_record_image, [image_height, image_width, image_channels]) print tf_record_image tf_record_label = tf.cast(tf_record_features['label'], tf.string) print tf_record_label print "------------------------------------------------------" sess.close() sess = tf.Session() sess.run(tf.global_variables_initializer()) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess,coord=coord) print sess.run(tf.equal(image, tf_record_image)) sess.run(tf_record_label) coord.request_stop() coord.join(threads) print "------------------------------------------------------" print sess.run(tf.image.central_crop(image, 0.1)) real_image = sess.run(image) bounding_crop = tf.image.crop_to_bounding_box( real_image, offset_height=0, offset_width=0, target_height=2, target_width=1) print sess.run(bounding_crop) print "------------------------------------------------------" real_image = sess.run(image) pad = tf.image.pad_to_bounding_box( real_image, offset_height=0, offset_width=0, target_height=4, target_width=4) print sess.run(pad) print "------------------------------------------------------" crop_or_pad = tf.image.resize_image_with_crop_or_pad( real_image, target_height=2, target_width=5) print sess.run(crop_or_pad) print "------------------------------------------------------" sess.close() sess = tf.Session() top_left_pixels = tf.slice(image, [0, 0, 0], [2, 2, 3]) flip_horizon = tf.image.flip_left_right(top_left_pixels) flip_vertical = tf.image.flip_up_down(flip_horizon) sess.run(tf.global_variables_initializer()) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess,coord=coord) print sess.run([top_left_pixels, flip_vertical]) print "------------------------------------------------------" top_left_pixels = tf.slice(image, [0, 0, 0], [2, 2, 3]) random_flip_horizon = tf.image.random_flip_left_right(top_left_pixels) random_flip_vertical = tf.image.random_flip_up_down(random_flip_horizon) print sess.run(random_flip_vertical) print "------------------------------------------------------" example_red_pixel = tf.constant([254., 2., 15.]) adjust_brightness = tf.image.adjust_brightness(example_red_pixel, 0.2) print sess.run(adjust_brightness) print "------------------------------------------------------" adjust_contrast = tf.image.adjust_contrast(image, -.5) print sess.run(tf.slice(adjust_contrast, [1, 0, 0], [1, 3, 3])) print "------------------------------------------------------" adjust_hue = tf.image.adjust_hue(image, 0.7) print sess.run(tf.slice(adjust_hue, [1, 0, 0], [1, 3, 3])) print "------------------------------------------------------" adjust_saturation = tf.image.adjust_saturation(image, 0.4) print sess.run(tf.slice(adjust_saturation, [1, 0, 0], [1, 3, 3])) print "------------------------------------------------------" gray = tf.image.rgb_to_grayscale(image) print sess.run(tf.slice(gray, [0, 0, 0], [1, 3, 1])) print "------------------------------------------------------" hsv = tf.image.rgb_to_hsv(tf.image.convert_image_dtype(image, tf.float32)) print sess.run(tf.slice(hsv, [0, 0, 0], [3, 3, 3])) print "------------------------------------------------------" rgb_hsv = tf.image.hsv_to_rgb(hsv) rgb_grayscale = tf.image.grayscale_to_rgb(gray) print rgb_hsv, rgb_grayscale print "------------------------------------------------------"
參考資料:
《面向機器智能的TensorFlow實踐》
歡迎加我微信交流:qingxingfengzi
我的微信公眾號:qingxingfengzigz
我老婆張幸清的微信公眾號:qingqingfeifangz