Python-CIFAR-10二进制格式数据集转为JPG格式

Python源码

# -*- coding: utf-8 -*-

"""
@Date: 2018/12/25

@Author: dreamhome

@Summary:
"""
import cv2
import numpy as np
import os

# 文件夹名
str_2 = './train_cifar10'
str_1 = './test_cifar10'

if os.path.exists(str_1) == False:
    os.mkdir(str_1)
if os.path.exists(str_2) == False:
    os.mkdir(str_2)


def unpickle(file):
    import pickle
    fo = open(file, 'rb')
    dict = pickle.load(fo, encoding='bytes')
    fo.close()
    return dict


def cifar_jpg(dir_file):
    for j in range(1, 6):
        dataName = dir_file + '/' + "data_batch_" + str(j)
        Xtr = unpickle(dataName)
        print(len(Xtr[b'labels']))
        print(dataName + " is loading...")
        for i in range(0, 10000):
            img = np.reshape(Xtr[b'data'][i], (3, 32, 32))
            img = img.transpose(1, 2, 0)
            picName = './train_cifar10/' + str(Xtr[b'labels'][i]) + '_' + str(i + (j - 1) * 10000) + '.jpg'
            cv2.imwrite(picName, img)
        print(dataName + " loaded.")

    print("test_batch is loading...")
    testName = dir_file + '/' + 'test_batch'
    testXtr = unpickle(testName)
    for i in range(0, 10000):
        img = np.reshape(testXtr[b'data'][i], (3, 32, 32))
        img = img.transpose(1, 2, 0)
        picName = './test_cifar10/' + str(testXtr[b'labels'][i]) + '_' + str(i) + '.jpg'
        cv2.imwrite(picName, img)
    print("test_batch loaded.")

    return


if __name__ == '__main__':
    dir_file = './cifar-10-batches'
    cifar_jpg(dir_file)

发布了62 篇原创文章 · 获赞 62 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/DreamHome_S/article/details/85244261