TensorFlow支持JPG、PNG圖像格式,RGB、RGBA顏色空間。圖像用與圖像尺寸相同(height*width*chnanel)張量表示。通道表示爲包含每一個通道顏色數量標量秩1張量。圖像全部像素存在磁盤文件,須要被加載到內存。python
圖像加載與二進制文件相同。圖像須要解碼。輸入生成器(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文件存儲數據與標籤。作好圖像預處理並保存結果。dom
最好在預處理階段完成圖像操做,裁剪、縮放、灰度調整等。圖像加載後,翻轉、扭曲,使輸入網絡訓練信息多樣化,緩解過擬合。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,相對圖像中心,裁剪或填充同時進行。ui
翻轉,每一個像素位置沿水平或垂真方向翻轉。隨機翻轉圖像,能夠防止過擬合。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