利用tensorflow训练自己的图片数据(1)——预处理

来源:互联网 发布:java策略模式接口意义 编辑:程序博客网 时间:2024/05/15 03:24

一. 准备原始数据

首先,我们需要准备训练的原始数据,本次训练为图像分类识别,因而一开始,笔者从网上随机的下载了Dog的四种类别:husky,jiwawa,poodle,qiutian。每种类别30种,一共120张图片。在训练之前,需要做的就是进行图像的预处理,即将这些大小不一的原始图片转换成我们训练需要的shape。

下载的原始图片分别放到同一文件的不同文件夹下,如:

二. 编程实现

该部分包括:制作Tfrecords,读取Tfrecords数据获得iamge和label,打印验证并保存生成的图片。

[python] view plain copy
  1. #将原始图片转换成需要的大小,并将其保存  
  2. #========================================================================================  
  3. import os    
  4. import tensorflow as tf    
  5. from PIL import Image    
  6.     
  7. #原始图片的存储位置  
  8. orig_picture = 'E:/train_test/train_data/generate_sample/'  
  9.   
  10. #生成图片的存储位置  
  11. gen_picture = 'E:/Re_train/image_data/inputdata/'  
  12.   
  13. #需要的识别类型  
  14. classes = {'husky','jiwawa','poodle','qiutian'}   
  15.   
  16. #样本总数  
  17. num_samples = 120   
  18.      
  19. #制作TFRecords数据    
  20. def create_record():    
  21.     writer = tf.python_io.TFRecordWriter("dog_train.tfrecords")    
  22.     for index, name in enumerate(classes):    
  23.         class_path = orig_picture +"/"+ name+"/"    
  24.         for img_name in os.listdir(class_path):    
  25.             img_path = class_path + img_name    
  26.             img = Image.open(img_path)    
  27.             img = img.resize((6464))    #设置需要转换的图片大小  
  28.             img_raw = img.tobytes()      #将图片转化为原生bytes    
  29.             print (index,img_raw)    
  30.             example = tf.train.Example(    
  31.                features=tf.train.Features(feature={    
  32.                     "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[index])),    
  33.                     'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))    
  34.                }))    
  35.             writer.write(example.SerializeToString())    
  36.     writer.close()    
  37.       
  38. #=======================================================================================  
  39. def read_and_decode(filename):    
  40.     # 创建文件队列,不限读取的数量    
  41.     filename_queue = tf.train.string_input_producer([filename])    
  42.     # create a reader from file queue    
  43.     reader = tf.TFRecordReader()    
  44.     # reader从文件队列中读入一个序列化的样本    
  45.     _, serialized_example = reader.read(filename_queue)    
  46.     # get feature from serialized example    
  47.     # 解析符号化的样本    
  48.     features = tf.parse_single_example(    
  49.         serialized_example,    
  50.         features={    
  51.             'label': tf.FixedLenFeature([], tf.int64),    
  52.             'img_raw': tf.FixedLenFeature([], tf.string)    
  53.         })    
  54.     label = features['label']    
  55.     img = features['img_raw']    
  56.     img = tf.decode_raw(img, tf.uint8)    
  57.     img = tf.reshape(img, [64643])    
  58.     #img = tf.cast(img, tf.float32) * (1. / 255) - 0.5    
  59.     label = tf.cast(label, tf.int32)    
  60.     return img, label    
  61.   
  62. #=======================================================================================  
  63. if __name__ == '__main__':    
  64.     create_record()    
  65.     batch = read_and_decode('dog_train.tfrecords')    
  66.     init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())    
  67.         
  68.     with tf.Session() as sess: #开始一个会话      
  69.         sess.run(init_op)      
  70.         coord=tf.train.Coordinator()      
  71.         threads= tf.train.start_queue_runners(coord=coord)    
  72.           
  73.         for i in range(num_samples):      
  74.             example, lab = sess.run(batch)#在会话中取出image和label      
  75.             img=Image.fromarray(example, 'RGB')#这里Image是之前提到的   
  76.             img.save(gen_picture+'/'+str(i)+'samples'+str(lab)+'.jpg')#存下图片;注意cwd后边加上‘/’      
  77.             print(example, lab)      
  78.         coord.request_stop()      
  79.         coord.join(threads)     
  80.         sess.close()    
  81.           
  82. #========================================================================================    
运行程序,得到的结果都保存在gen_picture文件中。一方面,我们可以通过生成图片的命名,验证label是否与图片对应;另一方面,我们将生成的120张图片按照图片命名中的label,分别放到四个不同的文件夹下,作为后续操作的inputdata数据,如下:

此处生成的四类图片husky,jiwawa,poodle,qiutian;其shape = 64 x 64,大小一致,一共120张

阅读全文
0 0
原创粉丝点击