1. 程式人生 > >如何使用tf.data讀取tfrecords資料集2

如何使用tf.data讀取tfrecords資料集2

在檢查完了資料是否一樣後就要開始轉圖片格式,其實不一定要這一步,但是我怕資料的型別不同影響資料集的效果。

import os
import tensorflow as tf
from PIL import Image
import PIL
import matplotlib.pyplot as plt
import numpy as np
from scipy.misc import imread, imsave, imresize

cwd = r'/home/hehe/python/dataset1/washing/'

num=0
#使用os.listdir()獲取cwd裡面所有檔案,然後轉化格式儲存
for img_name in os.listdir(cwd):
    img_path = cwd + img_name


    img = Image.open(img_path)
    img = img.resize((100, 100))
     # # img.show()
    img.save('/home/hehe/python/load_cifar10/datadir/washing/washing{}.JPEG'.format(num))
    num += 1
print("change format finish")
   

這個是我轉化圖片的完整程式碼,在cwd裡面使用os.listdir得到所有資料的名字,然後使用PIL模組中的resize來定製大小,最後使用img.save來儲存資料到指定的資料集中。

好了,這個就是轉換圖片的程式碼。接下來就要使用程式碼為所有的資料打標籤,然後shuffle

#下面的程式碼是為了生成list.txt , 把不同資料夾下的圖片和 數字label對應起來
import os

classes = {'bookrack':1 ,'cleaner':2, 'fan':3, 'lamp':4, 'microwave':5,
           'soft':6, 'bed':7, 'chair':0, 'washing':8, 'desk':9}
data_dir = r'/home/hehe/python/load_cifar10/datadir/'
output_path = 'list.txt'
fd = open(output_path, 'w')
for class_name in classes.keys():
    images_list = os.listdir(data_dir + class_name)
    for image_name in images_list:
        fd.write('{}/{} {}\n'.format(class_name, image_name, classes[class_name]))
fd.close()
print('finish task')

在classes裡面定義好型別,字典裡面key是資料夾的名字,value是lable。下面的程式碼是把所有檔名打亂,相當於shuffle效果

#隨機生成訓練集和驗證集(在總量中隨機選取_NUM_VALIDATION=100個樣本作為驗證集)

import random
_NUM_VALIDATION = 2000
_RANDOM_SEED = 0
list_path = 'list.txt'
train_list_path = 'list_train.txt'
val_list_path = 'list_val.txt'
fd = open(list_path)
lines = fd.readlines()
fd.close()
random.seed(_RANDOM_SEED)
random.shuffle(lines)
fd = open(train_list_path, 'w')
for line in lines[_NUM_VALIDATION:]:
    fd.write(line)
fd.close()
fd = open(val_list_path, 'w')
for line in lines[:_NUM_VALIDATION]:
    fd.write(line)
fd.close()

也有另外一種比較簡單的方案

#隨機生成訓練集和驗證集(在總量中隨機選取_NUM_VALIDATION=100個樣本作為驗證集)


import random


ratio=0.2                #選擇0.2,那麼意味著你的測試集只有20%,訓練集80%
list_path = 'list.txt'
train_list_path = 'list_train.txt'
val_list_path = 'list_val.txt'
fd = open(list_path)
lines = fd.readlines()
_NUM_VALIDATION = int(len(lines)*ratio)
_RANDOM_SEED = 0
fd.close()
random.seed(_RANDOM_SEED)
random.shuffle(lines)
fd = open(train_list_path, 'w')
for line in lines[_NUM_VALIDATION:]:
    fd.write(line)
fd.close()
fd = open(val_list_path, 'w')
for line in lines[:_NUM_VALIDATION]:
    fd.write(line)
fd.close()

這種方案只需要改變ratio的大小就夠了,很方便