CIFAR10和CIFAR100转图片

昨天从csdn上看了一个,结果转出来图片是偏蓝的,效果如下:

资料发现是cv2的色彩空间正好是反着的,按资料里改一下就行了,或者我重新写了一份:

CIFAR10:

import numpy as np 
import pickle as pkl 
import os
from PIL import Image
import matplotlib.pyplot as plt 

train_list = [
        ['data_batch_1', 'c99cafc152244af753f735de768cd75f'],
        ['data_batch_2', 'd4bba439e000b95fd0a9bffe97cbabec'],
        ['data_batch_3', '54ebc095f3ab1f0389bbae665268c751'],
        ['data_batch_4', '634d18415352ddfa80567beed471001a'],
        ['data_batch_5', '482c414d41f54cd18b22e5b47cb7c3cb'],
    ]

test_list = [
        ['test_batch', '40351d587109b95175f43aff81a1287e'],
    ]

count = 0
for file_name, checksum in train_list:
	with open(file_name, 'rb') as f:
		entry = pkl.load(f, encoding='latin1')
		data, label = np.array(entry['data']).reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1), entry['labels']
		if not os.path.exists('train'):
			os.mkdir('train')
			for i in range(10):
				os.mkdir(os.path.join('train', str(i)))
		for i in range(data.shape[0]):
			count = count + 1
			img = Image.fromarray(data[i])
			img.save(os.path.join('train', str(label[i]), str(count)+'.png'))

for file_name, checksum in test_list:
	with open(file_name, 'rb') as f:
		entry = pkl.load(f, encoding='latin1')
		data, label = np.array(entry['data']).reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1), entry['labels']
		if not os.path.exists('val'):
			os.mkdir('val')
			for i in range(10):
				os.mkdir(os.path.join('val', str(i)))
		for i in range(data.shape[0]):
			count = count + 1
			img = Image.fromarray(data[i])
			img.save(os.path.join('val', str(label[i]), str(count)+'.png'))

CIFAR100:

import os
from PIL import Image
ROOT_PATH='/cache/cifar-100-python/cifar-100-python'
TO_ROOT='/cache/cifar100V2'
def unpickle(file):
    import pickle
    with open(file, 'rb') as fo:
        dict = pickle.load(fo, encoding='latin1')
    return dict
meta_dict=unpickle(os.path.join(ROOT_PATH,'meta'))
train_dict=unpickle(os.path.join(ROOT_PATH,'train'))
test_dict=unpickle(os.path.join(ROOT_PATH,'test'))
os.mkdir(TO_ROOT)
os.mkdir(os.path.join(TO_ROOT,'train'))
os.mkdir(os.path.join(TO_ROOT,'val'))
for i in range(100):
    os.mkdir(os.path.join(TO_ROOT,'train',str(i)))
    os.mkdir(os.path.join(TO_ROOT,'val',str(i)))
count=0
data, label = np.array(train_dict['data']).reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1), train_dict['fine_labels']
for i in range(data.shape[0]):
    count = count + 1
    img = Image.fromarray(data[i])
    img.save(os.path.join(TO_ROOT,'train', str(label[i]), str(count)+'.png'))
data, label = np.array(test_dict['data']).reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1), test_dict['fine_labels']
for i in range(data.shape[0]):
    count = count + 1
    img = Image.fromarray(data[i])
    img.save(os.path.join(TO_ROOT,'val', str(label[i]), str(count)+'.png'))
posted @ 2021-04-01 16:50  别再闹了  阅读(543)  评论(0编辑  收藏  举报