LoginSignup
1

More than 5 years have passed since last update.

cifarとCUCUMBER-9データセットから画像を取り出す

Posted at

Python3でnumpyの配列から画像を生成する、ってタイトルの方が良いかも(あえてニッチな方で(^^;

cifarは飛行機やら猫やら、cucumberは(その名の通り)きゅうりの画像セットです。機械学習に使いやすいようにnumpyの配列形式で配布されているんですが、実際の中身を覗いてみたいというのが動機です。

https://www.cs.toronto.edu/~kriz/cifar.html
https://github.com/workpiles/CUCUMBER-9

cucmberはciferとフォーマットを揃えているらしいんですが、実際には異なっていまして、それぞれ別個の処理が必要でした。Tensorflowにはcucumber形式の方が便利なのかな…?(理由は分かっていません)

data.shape = (10000, 3072) # cifar-10
data.shape = (1485, 1024) # CUCUMBER-9

サンプルプログラムは以下の通りです。Python2の場合、cPickleを使ってください。numpyとPILが必要です。

import numpy as np
import _pickle,random
from PIL import Image

def unpickle(file):
    fo = open(file, 'rb')
    dict = _pickle.load(fo, encoding='latin-1')
    fo.close()
    return dict

def image_from_cifar(index,dic):
    name = dic['filenames'][index]
    data = dic['data'][index].reshape(3, 32, 32).transpose(1, 2, 0) # shape=(32, 32, 3)
    img = Image.fromarray(data, 'RGB')
    print(name)
    img.save(name)

def image_from_cucumber(index,dic):
    name = dic['filenames'][index]
    r = dic['data'][index*3]
    g = dic['data'][index*3+1]
    b = dic['data'][index*3+2]
    data = np.array([r,g,b]).T.reshape(32,32,3)
    img = Image.fromarray(data, 'RGB')
    print(name)
    img.save(name)

if __name__ == "__main__":
    dic = unpickle('cifar-10-batches-py/data_batch_1')
    image_from_cifar(random.randint(0,len(dic['filenames'])),dic)

    dic = unpickle('CUCUMBER-9-master/prototype_1/cucumber-9-python/data_batch_1')
    image_from_cucumber(random.randint(0,len(dic['filenames'])),dic)

それぞれのデータセットをカレントディレクトリに置いた状態で実行すると、ランダムに一枚取り出して画像として保存してくれます。

tabby_cat_s_000125.png

2L_00153.jpg

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1