CIFAR-100 をpngで出力

先日読み込んで見たけど今度はpng形式で出力してみた。
png出力先のパスに'train'と'test'ディレクトリを作成してそれぞれの画像を出力する。

import os, pickle
from PIL import Image

class Cifar100:
    topdirname = 'cifar-100-python'
    width, height = 32, 32
    def __init__(self, extractedpath):
        dirpath = os.path.join(extractedpath, Cifar100.topdirname)
        with open(os.path.join(dirpath, 'meta'), 'rb') as fp:
            self.meta = pickle.load(fp)
        with open(os.path.join(dirpath, 'train'), 'rb') as fp:
            self.train = pickle.load(fp, encoding='latin-1')
        with open(os.path.join(dirpath, 'test'), 'rb') as fp:
            self.test = pickle.load(fp, encoding='latin-1')

    def _out_images(self, path, data, filename):
        for (d,f) in zip(data, filename):
            im = Image.new('RGB', (Cifar100.width, Cifar100.height), (0xff, 0xff, 0xff))
            putdata = []
            for wh in range(Cifar100.width*Cifar100.height):
                r = d[wh]
                g = d[wh+Cifar100.width*Cifar100.height]
                b = d[wh+2*Cifar100.width*Cifar100.height]
                putdata.append((r, g, b))
            im.putdata(putdata)
            im.save(os.path.join(path, f))
            print(os.path.join(path, f))

    def out_images(self, path):
        trainpath = os.path.join(path, 'train')
        if not os.path.isdir(trainpath):
            os.mkdir(trainpath)
        self._out_images(trainpath, self.train['data'], self.train['filenames'])
        testpath = os.path.join(path, 'test')
        if not os.path.isdir(testpath):
            os.mkdir(testpath)
        self._out_images(testpath, self.test['data'], self.test['filenames'])

if __name__ == '__main__':
    cifar = Cifar100('ファイル解答先のパス')
    cifar.out_images('png出力先のパス')

コメント

このブログの人気の投稿

Python SQLite スレッド間でコネクションの使いまわしは出来ない

slackでgeneralの投稿を全削除する

Google location history(JSON形式)をCSVファイルにする