|
读取海量图像文件和Label标签,并保存数据:
(1)准备我们的图像数据,Train文件夹图像+Labels、Test文件夹图像+Labels
(2)读取Train文件夹图像+Labels、Test文件夹图像+Labels存储为Tensorflow需要的数据格式
(3)写入.pkl文件,方便下次加载直接使用;- # -*- coding: utf-8 -*-
- """
- Created on Sat Aug 26 21:52:50 2017
- @author: Administrator
- """
- import pickle
- from PIL import Image
- import numpy as np
- import os
- def load_Img(imgDir,imgFoldName):
- imgs = os.listdir(imgDir+imgFoldName)
- imgNum = len(imgs)
- data = np.empty((imgNum,28,28,1),dtype="uint8")
- for i in range (imgNum):
- # img = Image.open(imgDir+imgFoldName+"/"+imgs[i])
- img = Image.open(imgDir+imgFoldName+"/"+ str(i) + '.png' )
- arr = np.asarray(img,dtype="uint8")
- arr = np.reshape(arr, [28,28,1] )
- data[i,:,:,:] = arr
- return data
- def dense_to_one_hot(labels_dense, num_classes):
- """Convert class labels from scalars to one-hot vectors."""
- num_labels = labels_dense.shape[0]
- index_offset = np.arange(num_labels) * num_classes
- labels_one_hot = np.zeros((num_labels, num_classes))
- labels_one_hot.flat[index_offset.astype(int) + labels_dense.ravel().astype(int)] = 1
- return labels_one_hot
- def load_Label(LabelDir,LabelFoldName, one_hot, num_classes):
- Labs = os.listdir(LabelDir+LabelFoldName)
- File = open(LabelDir+LabelFoldName + Labs[1])
- File.seek(0,0)
- Dstr = File.read();
- data = str.split(Dstr,',')
- Label = np.array(data, dtype=np.float64)
- File.close()
- if one_hot:
- return dense_to_one_hot(Label, num_classes);
- return Label
-
- imgDir = "./Test/"
- imgFoldName = "test"
- test_images = load_Img("./Test/","test")
- train_images = load_Img("./Train/","train")
- LabelDir = "D:/Deep_learning_TensorFlow_python/Learning_DayByDay/Mnist/Test/"
- LabelFoldName = ""
- train_labels = load_Label("./Train/","", True, 10)
- test_labels = load_Label("./Test/","", True, 10)
- # 保存数据
- pickle_data = open('./PKL_mnist/train_images.pkl','wb');
- pickle.dump(train_images, pickle_data);
- pickle_data.close();
- pickle_data = open('./PKL_mnist/test_images.pkl','wb');
- pickle.dump(test_images, pickle_data);
- pickle_data.close();
- pickle_data = open('./PKL_mnist/train_labels.pkl','wb');
- pickle.dump(train_labels, pickle_data);
- pickle_data.close();
- pickle_data = open('./PKL_mnist/test_labels.pkl','wb');
- pickle.dump(test_labels, pickle_data);
- pickle_data.close();
- print('写入PKL文件完成!!!')
复制代码
百度网盘链接:
链接:http://pan.baidu.com/s/1i4BbOlJ
具体链接在halcom.cn论坛,联系人QQ:3283892722
该论坛是一个学习交流平台,我会逐一的和大家分享学习。
欢迎大家录制视频,你可在论坛进行打赏分享。
视频专用播放器:http://halcom.cn/forum.php?mod=viewthread&tid=258&extra=page%3D1
|
|