LoginSignup
1
2

More than 3 years have passed since last update.

Jupyterで簡単な画像認識をしてみた

Posted at

概要

https://qiita.com/uz29/items/ec854106355bf783e316
前回で準備が終わったのでまずは既存の学習モデルであるVGG16を使って画像判別プログラムを作った。

ライブラリのインポートとモデルのインポート

初回はモデルのダウンロードが行われる。

import glob
import pprint
import numpy as np
import tensorflow as tf
from PIL import Image

model = tf.keras.applications.vgg16.VGG16(weights='imagenet')

予測スクリプト

フォルダに入っている画像をまとめて予測にかけたかったので、globでパス一覧を取得しそれぞれの画像の配列を作成している。
予測は一度の関数の呼び出しで複数画像を同時に処理できるらしい。

#フォルダ内の写真を一括で予測
file_list = glob.glob("./images/*")

pil = []
imgs = []
for path in file_list:
    # 画像読み込み
    img_pil = tf.keras.preprocessing.image.load_img(path, target_size=(224, 224))
    pil.append(img_pil)
    # 画像を配列に変換
    img = tf.keras.preprocessing.image.img_to_array(img_pil)
    # 4次元配列に変換
    imgs.append(img)
imgs = np.stack(imgs, 0)

# 前処理
img_p = tf.keras.applications.vgg16.preprocess_input(imgs)
# 予測
predict = model.predict(img_p)
result = tf.keras.applications.vgg16.decode_predictions(predict, top=5)

結果の表示

予測結果は以下で見ることができる。

pprint.pprint(result[0])
plt.imshow(pil[0])

[('n02124075', 'Egyptian_cat', 0.42277277),
('n02123159', 'tiger_cat', 0.18187998),
('n02123045', 'tabby', 0.12070633),
('n02883205', 'bow_tie', 0.0892005),
('n02127052', 'lynx', 0.024664408)]
image.png

pprint.pprint(result[1])
plt.imshow(pil[1])

[('n02119789', 'kit_fox', 0.6857688),
('n02119022', 'red_fox', 0.24295172),
('n02120505', 'grey_fox', 0.065218925),
('n02114855', 'coyote', 0.004371826),
('n02115913', 'dhole', 0.00046840237)]
image.png

pprint.pprint(result[2])
plt.imshow(pil[2])

[('n02138441', 'meerkat', 0.9073721),
('n02137549', 'mongoose', 0.092063464),
('n02447366', 'badger', 0.00037895824),
('n02361337', 'marmot', 8.514335e-05),
('n02441942', 'weasel', 2.4436611e-05)]
image.png

動物の細かい種類はVGG16に含まれていなくて異なる場合もあるがおおむね正確な種類を返してくれている。
今後は自分で学習モデルを作って予測させてみたい。

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