python實現cifar10數據集的可視化

在學習tensorflow的mnist和cifar實例的時候,官方文檔給出的講解都是一張張圖片,直觀清晰,當我們看到程序下載下來的數據的時候,寶寶都驚呆了,都是二進制文件,這些二進制文件還不小,用文本編輯器打開看也看不懂,要是將數據再現爲圖像,多好!

(1)CIFAR-10數據集介紹

① CIFAR-10數據集包含60000個32*32的彩色圖像,共有10類。有50000個訓練圖像和10000個測試圖像。
數據集分爲5個訓練塊和1個測試塊,每個塊有10000個圖像。測試塊包含從每類隨機選擇的1000個圖像。訓練塊以隨機的順序包含這些圖像,但一些訓練塊可能比其它類包含更多的圖像。訓練塊每類包含5000個圖像。
②data——1個10000*3072大小的uint8s數組。數組的每行存儲1張32*32的圖像。第1個1024包含紅色通道值,下1個包含綠色,最後的1024包含藍色。圖像存儲以行順序爲主,所以數組的前32列爲圖像第1行的紅色通道值。
labels——1個10000數的範圍爲0~9的列表。索引i的數值表示數組data中第i個圖像的標籤。
③數據集中包含另外1個叫batches.meta的文件。它也包含1個Python字典對象。有如下列元素:
label_names——1個10元素的列表,給labels中的數值標籤以有意義的名稱。例如,label_names[0] == “airplane”, label_names[1] == “automobile”等。

(2)下載python版本的cifar數據

先給個cifar數據下載鏈接:http://www.cs.toronto.edu/~kriz/cifar.html
鏈接上提到三個數據版本,分別是python,matlab,binary版本,分別適合python,matlab,C程序
我們用python實現cifar數據轉化爲圖像,當然要用Python版本的啦
下載好了,我們就可以用下面的代碼啦

(3)代碼

# -*- coding:utf-8 -*-
import pickle as p
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as plimg
from PIL import Image
def load_CIFAR_batch(filename):
    """ load single batch of cifar """
    with open(filename, 'rb')as f:
        datadict = p.load(f)
        X = datadict['data']
        Y = datadict['labels']
        X = X.reshape(10000, 3, 32, 32)
        Y = np.array(Y)
        return X, Y

def load_CIFAR_Labels(filename):
    with open(filename, 'rb') as f:
        lines = [x for x in f.readlines()]
        print(lines)


if __name__ == "__main__":
    load_CIFAR_Labels("/data/cifar-10-batches-py/batches.meta")
    imgX, imgY = load_CIFAR_batch("/data/cifar-10-batches-py/data_batch_1")
    print imgX.shape
    print "正在保存圖片:"
    for i in xrange(imgX.shape[0]):
        imgs = imgX[i - 1]
        if i < 100:#只循環100張圖片,這句註釋掉可以便利出所有的圖片,圖片較多,可能要一定的時間
            img0 = imgs[0]
            img1 = imgs[1]
            img2 = imgs[2]
            i0 = Image.fromarray(img0)
            i1 = Image.fromarray(img1)
            i2 = Image.fromarray(img2)
            img = Image.merge("RGB",(i0,i1,i2))
            name = "img" + str(i)
            img.save("/data/images/"+name,"png")#文件夾下是RGB融合後的圖像
            for j in xrange(imgs.shape[0]):
                img = imgs[j - 1]
                name = "img" + str(i) + str(j) + ".png"
                print "正在保存圖片" + name
                plimg.imsave("/data/image/" + name, img)#文件夾下是RGB分離的圖像

    print "保存完畢."
發佈了41 篇原創文章 · 獲贊 74 · 訪問量 27萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章