TensorFlow筆記五:將cifar10數據文件復原成圖片格式

cifar10數據集(http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz)源格式是數據文件,由於訓練須要轉換成圖片格式python

轉換代碼:測試

注意文件路徑改爲本身的文件路徑,train文件夾須要本身建,等待轉換完成spa

from scipy.misc import imsave
import numpy as np

# 解壓 返回解壓後的字典
def unpickle(file):
    import pickle as pk
    fo = open(file, 'rb')
    dict = pk.load(fo,encoding='iso-8859-1')
    fo.close()
    return dict

# 生成訓練集圖片
for j in range(1, 6):
    dataName = "cifar-10-python/cifar-10-batches-py/data_batch_" + str(j)  # 讀取當前目錄下的data_batch1~5文件。
    Xtr = unpickle(dataName)
    print (dataName + " is loading...")

    for i in range(0, 10000):
        img = np.reshape(Xtr['data'][i], (3, 32, 32))  # Xtr['data']爲圖片二進制數據
        img = img.transpose(1, 2, 0)  # 讀取image
        picName = 'train/' + str(Xtr['labels'][i]) + '_' + str(i + (j - 1)*10000) + '.jpg'
        # Xtr['labels']爲圖片的標籤,值範圍0-9,本文中,train文件夾須要存在,並與腳本文件在同一目錄下。
        imsave(picName, img)
    print (dataName + " loaded.")

print ("test_batch is loading...")

# 生成測試集圖片
testXtr = unpickle("test_batch")
for i in range(0, 10000):
    img = np.reshape(testXtr['data'][i], (3, 32, 32))
    img = img.transpose(1, 2, 0)
    picName = 'test/' + str(testXtr['labels'][i]) + '_' + str(i) + '.jpg'
    imsave(picName, img)
print ("test_batch loaded.")
相關文章
相關標籤/搜索