分享

学习TensorFlow,生成tensorflow输入输出的图像格式

 雪柳花明 2017-03-17

TensorFLow能够识别的图像文件,可以通过numpy,使用tf.Variable或者tf.placeholder加载进tensorflow;也可以通过自带函数(tf.read)读取,当图像文件过多时,一般使用pipeline通过队列的方法进行读取。下面我们介绍两种生成tensorflow的图像格式的方法,供给tensorflow的graph的输入与输出。

1

[python] view plain copy
在CODE上查看代码片派生到我的代码片
  1. import cv2  
  2. import numpy as np  
  3. import h5py  
  4.   
  5. height = 460  
  6. width = 345  
  7.   
  8. with h5py.File('make3d_dataset_f460.mat','r') as f:  
  9.     images = f['images'][:]  
  10.       
  11. image_num = len(images)  
  12.   
  13. data = np.zeros((image_num, height, width, 3), np.uint8)  
  14. data = images.transpose((0,3,2,1))  


先生成图像文件的路径:ls *.jpg> list.txt

[python] view plain copy
在CODE上查看代码片派生到我的代码片
  1. import cv2  
  2. import numpy as np  
  3.   
  4. image_path = './'  
  5. list_file  = 'list.txt'  
  6. height = 48  
  7. width = 48  
  8.   
  9. image_name_list = [] # read image  
  10. with open(image_path + list_file) as fid:  
  11.     image_name_list = [x.strip() for x in fid.readlines()]  
  12. image_num = len(image_name_list)  
  13.   
  14. data = np.zeros((image_num, height, width, 3), np.uint8)  
  15.   
  16. for idx in range(image_num):  
  17.     img = cv2.imread(image_name_list[idx])  
  18.     img = cv2.resize(img, (height, width))  
  19.     data[idx, :, :, :] = img  


2 Tensorflow自带函数读取

[python] view plain copy
在CODE上查看代码片派生到我的代码片
  1. def get_image(image_path):  
  2.     """Reads the jpg image from image_path. 
  3.     Returns the image as a tf.float32 tensor 
  4.     Args: 
  5.         image_path: tf.string tensor 
  6.     Reuturn: 
  7.         the decoded jpeg image casted to float32 
  8.     """  
  9.     return tf.image.convert_image_dtype(  
  10.         tf.image.decode_jpeg(  
  11.             tf.read_file(image_path), channels=3),  
  12.         dtype=tf.uint8)  


 pipeline读取方法

[python] view plain copy
在CODE上查看代码片派生到我的代码片
  1. # Example on how to use the tensorflow input pipelines. The explanation can be found here ischlag..  
  2. import tensorflow as tf  
  3. import random  
  4. from tensorflow.python.framework import ops  
  5. from tensorflow.python.framework import dtypes  
  6.   
  7. dataset_path      = "/path/to/your/dataset/mnist/"  
  8. test_labels_file  = "test-labels.csv"  
  9. train_labels_file = "train-labels.csv"  
  10.   
  11. test_set_size = 5  
  12.   
  13. IMAGE_HEIGHT  = 28  
  14. IMAGE_WIDTH   = 28  
  15. NUM_CHANNELS  = 3  
  16. BATCH_SIZE    = 5  
  17.   
  18. def encode_label(label):  
  19.   return int(label)  
  20.   
  21. def read_label_file(file):  
  22.   f = open(file, "r")  
  23.   filepaths = []  
  24.   labels = []  
  25.   for line in f:  
  26.     filepath, label = line.split(",")  
  27.     filepaths.append(filepath)  
  28.     labels.append(encode_label(label))  
  29.   return filepaths, labels  
  30.   
  31. # reading labels and file path  
  32. train_filepaths, train_labels = read_label_file(dataset_path + train_labels_file)  
  33. test_filepaths, test_labels = read_label_file(dataset_path + test_labels_file)  
  34.   
  35. # transform relative path into full path  
  36. train_filepaths = [ dataset_path + fp for fp in train_filepaths]  
  37. test_filepaths = [ dataset_path + fp for fp in test_filepaths]  
  38.   
  39. # for this example we will create or own test partition  
  40. all_filepaths = train_filepaths + test_filepaths  
  41. all_labels = train_labels + test_labels  
  42.   
  43. all_filepaths = all_filepaths[:20]  
  44. all_labels = all_labels[:20]  
  45.   
  46. # convert string into tensors  
  47. all_images = ops.convert_to_tensor(all_filepaths, dtype=dtypes.string)  
  48. all_labels = ops.convert_to_tensor(all_labels, dtype=dtypes.int32)  
  49.   
  50. # create a partition vector  
  51. partitions = [0] * len(all_filepaths)  
  52. partitions[:test_set_size] = [1] * test_set_size  
  53. random.shuffle(partitions)  
  54.   
  55. # partition our data into a test and train set according to our partition vector  
  56. train_images, test_images = tf.dynamic_partition(all_images, partitions, 2)  
  57. train_labels, test_labels = tf.dynamic_partition(all_labels, partitions, 2)  
  58.   
  59. # create input queues  
  60. train_input_queue = tf.train.slice_input_producer(  
  61.                                     [train_images, train_labels],  
  62.                                     shuffle=False)  
  63. test_input_queue = tf.train.slice_input_producer(  
  64.                                     [test_images, test_labels],  
  65.                                     shuffle=False)  
  66.   
  67. # process path and string tensor into an image and a label  
  68. file_content = tf.read_file(train_input_queue[0])  
  69. train_image = tf.image.decode_jpeg(file_content, channels=NUM_CHANNELS)  
  70. train_label = train_input_queue[1]  
  71.   
  72. file_content = tf.read_file(test_input_queue[0])  
  73. test_image = tf.image.decode_jpeg(file_content, channels=NUM_CHANNELS)  
  74. test_label = test_input_queue[1]  
  75.   
  76. # define tensor shape  
  77. train_image.set_shape([IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS])  
  78. test_image.set_shape([IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS])  
  79.   
  80.   
  81. # collect batches of images before processing  
  82. train_image_batch, train_label_batch = tf.train.batch(  
  83.                                     [train_image, train_label],  
  84.                                     batch_size=BATCH_SIZE  
  85.                                     #,num_threads=1  
  86.                                     )  
  87. test_image_batch, test_label_batch = tf.train.batch(  
  88.                                     [test_image, test_label],  
  89.                                     batch_size=BATCH_SIZE  
  90.                                     #,num_threads=1  
  91.                                     )  
  92.   
  93. print "input pipeline ready"  
  94.   
  95. with tf.Session() as sess:  
  96.     
  97.   # initialize the variables  
  98.   sess.run(tf.initialize_all_variables())  
  99.     
  100.   # initialize the queue threads to start to shovel data  
  101.   coord = tf.train.Coordinator()  
  102.   threads = tf.train.start_queue_runners(coord=coord)  
  103.   
  104.   print "from the train set:"  
  105.   for i in range(20):  
  106.     print sess.run(train_label_batch)  
  107.   
  108.   print "from the test set:"  
  109.   for i in range(10):  
  110.     print sess.run(test_label_batch)  
  111.   
  112.   # stop our queue threads and properly close the session  
  113.   coord.request_stop()  
  114.   coord.join(threads)  
  115.   sess.close()  



参考资料

[1] http://ischlag./2016/06/19/tensorflow-input-pipeline-example/

[2] https:///blog/tensorflow-data-inputs-part1-placeholders-protobufs-queues/

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多