LoginSignup
2
1

More than 5 years have passed since last update.

matplotlibやKerasでの画像の扱い

Last updated at Posted at 2017-05-23

matplotlib

matplotlib の本家ドキュメントを参照しながら。
ここで "cat.jpg" は、高さ280ピクセル、幅300ピクセルのカラー画像とする。


import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img = mpimg.imread("cat.jpg")
primt(type(img)) # => <class 'numpy.ndarray'>
print(img.shape) # => (280, 300, 3) 280:高さ, 300:幅, 3:チャンネル(RGB)
print(img)
plt.imshow(img)
plt.show()

mping.imread() の戻り値は shape が (280, 300, 3) の numpy.ndarray で中身は、0から255までの整数である。

ちなみに、途中で img = img / 255.0 として、0から1までの小数に変換しても、plt.imshow() は問題なく画像を表示してくれる。

Keras

環境: TensorFlow 1.1

from tensorflow.contrib.keras.python.keras.preprocessing.image import load_img, img_to_array, array_to_img

img = load_img("cat.jpg")
img2 = img_to_array(img)
print(type(img)) # <class 'PIL.JpegImagePlugin.JpegImageFile'>
print(type(img2)) # <class 'numpy.ndarray'>
print(img2.shape) # (280, 300, 3)
print(img2) # [[[  39.   44.   40.] ...

Keras の load_img は PIL 形式での画像を読み込むので、配列に変換するためには、img_to_array() を使う。この配列の shape は matplotlib の imread() が返す配列と同じ。数値は 0 から 255 までの並びだが、型が小数になっているので、plt.imshow() で画像を表示するには、255 で割るか、img.as_type(np.uint8)などとして整数型に変換する必要がある。

ImageDataGenerator 経由で得る画像もデフォルトでは 0から255までの数値(型は小数)で表現されている。つまり、img_to_array() の戻り値と同じ。

2
1
0

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
2
1