这篇教程对cifar10数据集还原成图片写得很实用,希望能帮到您。
其代码如下
"""
cifar10数据可视化
label:
0 airplane
1 automobile
2 bird
3 cat
4 deer
5 dog
6 frog
7 horse
8 ship
9 truck
"""
import numpy as np
import os
rootdir='Download/cifar-10-batches-bin/'
file_dir=os.listdir(rootdir)
num=10000
for i in range(0,len(file_dir)):
path=os.path.join(rootdir,file_dir[i])
if str(file_dir[i])[-3:]=='bin' and os.path.isfile(path):
out_path=os.path.join(rootdir,'materials',file_dir[i][:-4])
if not os.path.exists(out_path):
#如果不存在,则创建目录
os.makedirs(out_path)
bytestream=open(path,"rb")
buf=bytestream.read(num*(1+32*32*3))
#print(buf)
bytestream.close()
data=np.frombuffer(buf,dtype=np.uint8)
#print(data)
data=data.reshape(num,1+32*32*3)
labels_images=np.hsplit(data,[1])
labels=labels_images[0].reshape(num)
images=labels_images[1].reshape(num,32,32,3)
label_path=os.path.join(rootdir,'materials')
fw=open(os.path.join(label_path,file_dir[i][:-4]+'.txt'),'w')
for numofimg in range(num):
img=np.reshape(images[numofimg],(3,32,32))
img=img.transpose(1,2,0)
import cv2
cv2.imwrite(out_path+'\{:05d}.jpg'.format(numofimg),img)
fw.write(out_path+'\{:05d}.jpg'.format(numofimg)+'\t'+str(labels[numofimg])) 深度学习与XGBoost在小数据集上的测评 CIFAR-10 Download |