如何将CIFAR-10数据集转化为图片
简单记录一下CIFAR-10数据集转图片的过程
1.首先在官网下载CIFAR-10数据集
官网下载
得到文件如下
2.想把他转化为jpg图片,从网上得到代码如下
# -*- coding: utf-8 -*-
from scipy.misc import imsave
import numpy as np
import pickle
# 解压缩,返回解压后的字典
def unpickle(file):
fo = open(file, 'rb')
dict = pickle.load(fo, encoding='latin1')
fo.close()
return dict
# 生成训练集图片,如果需要png格式,只需要改图片后缀名即可。
for j in range(1, 6):
dataName = "data_batch_" + str(j) # 读取当前目录下的data_batch12345文件,dataName其实也是data_batch文件的路径,本文和脚本文件在同一目录下。
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.")
结果报错
ImportError: cannot import name 'imsave' from 'scipy.misc'
分析:原来是新版本imsave已经被弃用了
解决方法
把from scipy.misc import imsave
换成import imageio
把save
换成imageio.imwrite
3.改正后完整代码
# -*- coding: utf-8 -*-
# from scipy.misc import imsave
import numpy as np
import pickle
import imageio
import os
trainDir = "train"
testDir = "test"
if not os.path.exists(trainDir):
os.makedirs(trainDir)
if not os.path.exists(testDir):
os.makedirs(testDir)
# 解压缩,返回解压后的字典
def unpickle(file):
fo = open(file, 'rb')
dict = pickle.load(fo, encoding='latin1')
fo.close()
return dict
# 生成训练集图片,如果需要png格式,只需要改图片后缀名即可。
for j in range(1, 6):
dataName = "cifar-10-batches-py\data_batch_" + str(j) # 读取当前目录下的data_batch12345文件,dataName其实也是data_batch文件的路径,本文和脚本文件在同一目录下。
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文件夹需要存在,并与脚本文件在同一目录下。
imageio.imwrite(picName, img)
print(dataName + " loaded.")
print("test_batch is loading...")
# 生成测试集图片
testXtr = unpickle("cifar-10-batches-py\\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'
imageio.imwrite(picName, img)
print("test_batch loaded.")
到此over
标签:10,Xtr,img,batch,CIFAR,dataName,import,data,图片 From: https://blog.csdn.net/qq_47571437/article/details/145117419