Home About
Jupyter Notebook , MNIST

Jupyter Notebook で MNIST の画像を表示させる

Jupyter Notebook を使ってデモするときに備えて、そのセットアップと画像の取り扱いを調べた。

0

事前準備

環境は以下の通り。

$ python3 --version
Python 3.9.2.

仮想環境をつくる。

$ python3 -m venv ./jupyter-notebook
$ source ./jupyter-notebook
(jupyter-notebook) $

肝心の Jupyter Notebook を入れる。

インストール詳細はこちら: https://jupyter.org/install

(jupyter-notebook) $ pip install notebook

必要なモジュールを入れる。

(jupyter-notebook) $ pip install tensorflow==2.13.0 pillow==10.0.0

Macbook Air Intel で作業したのですが、上記コマンドはエラーになり、use --use-feature=2020-resolver と言われた。 素直に --use-feature=2020-resolver 指定してインストールしたらうまくいきました。

Jupyter Notebook を起動する。

(jupyter-notebook) $ jupyter notebook

あとは、ブラウザが起動して Jupyter Notebook 画面が出ます。New → Notebook を選択して、Notebook ページに移動。

データを入手して先頭データを画像に変換

まずは、tf.keras.datasets.minst.load_data() を使って MNIST データを入手。

import tensorflow as tf

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train.shape

このコードを評価する。(Ctrl+Enter)

(60000, 28, 28)

と出力されます。

以下を評価すると、先頭画像データ (28,28) のテンソルが出力されます。

x_train[0]

このテンソルを PIL で画像に変換すれば(元に戻すというべきか)よいのか?

from PIL import Image

def toImage(imgTensor):
    img_size_x = imgTensor.shape[0]
    img_size_y = imgTensor.shape[1]
    img = Image.new('L', (img_size_x, img_size_y))
    for yIndex in range(img_size_y):
        for xIndex in range(img_size_x):
            value = imgTensor[yIndex][xIndex]
            img.putpixel((xIndex, yIndex), int(value))
    return img

このエントリーで以前書いたコードを手直ししただけ。

あとは、この toImage 関数を使って PIL の Image インスタンスを・・・評価するだけ?!でなんと表示できました。

この例では、1000番目の訓練データの画像を見てみます。

img = toImage(x_train[1000])
img

0

まとめ

今回書いたコード全体を掲載します。

import tensorflow as tf
from PIL import Image

def toImage(imgTensor):
    img_size_x = imgTensor.shape[0]
    img_size_y = imgTensor.shape[1]
    img = Image.new('L', (img_size_x, img_size_y))
    for yIndex in range(img_size_y):
        for xIndex in range(img_size_x):
            value = imgTensor[yIndex][xIndex]
            img.putpixel((xIndex, yIndex), int(value))
    return img        

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

img = toImage(x_train[1000])
img

以上です。

Liked some of this entry? Buy me a coffee, please.