画像分類は,画像からそのクラス名を求めるもの.
Keras では,ImageNet で事前学習済みのモデルを,簡単に使うことができる.
このページでは, Keras の ImageNet で事前学習済みの MobileNetV2, Inception Resnet, ResNet50, DenseNet 121, DenseNet 169, NASNetを用いて画像分類を行う.
Keras で利用可能な画像分類のモデルは,https://keras.io/api/applications/ で説明されている.
目次:
このページの URL: https://www.kkaneko.jp/db/imclassify/resnet50.html
参考文献:
このページの内容は,Google Colaboratory でも実行できる.
そのために,次の URL で,Google Colaboratory のノートブックを準備している.
次のリンクをクリックすると,Google Colaboratory のノートブックが開く. そして,Google アカウントでログインすると,Google Colaboratory のノートブック内のコードを実行することができる.Google Colaboratory のノートブックは書き換えて使うこともできる.このとき,書き換え後のものを,各自の Google ドライブ内に保存することもできる.
https://colab.research.google.com/drive/1c0uJaZB7B6SDTnxS_5FJukKd9FbYg4-e?usp=sharing
自分で,Google Colaboratory のノートブックを新規作成する場合(上のリンクを使わない)のため,手順を説明する.
パソコンを使う場合は,下に「前準備(パソコンを使う場合)」で説明している.
https://colab.research.google.com
Google Colab はオンラインの Python 開発環境. 使用するには Google アカウントが必要
システム Python を使うことができる(その場合,Python のインストールは行わない)
システム Python を用いるときは,pip, setuptools の更新は次のコマンドで行う.
sudo apt -y update sudo apt -y install python3-pip python3-setuptools
Ubuntu で,システム Python 以外の Python をインストールしたい場合は pyenv が便利である: 別ページで説明している.
Python の URL: http://www.python.org/
【Python, pip の使い方】
Python, pip は,次のコマンドで起動できる.
【Python 開発環境のインストール】
JupyterLab, spyder, nteract (Python 開発環境) のインストールは, Windows でコマンドプロンプトを管理者として実行し, 次のコマンドを実行.
python -m pip install -U pip setuptools jupyterlab jupyter jupyter-console jupytext nteract_on_jupyter spyder
詳しくは,: 別ページで説明している.
JupyterLab, spyder, nteract (Python 開発環境) のインストール: : 別ページで説明している.
Windows での pip の実行では,コマンドプロンプトを管理者として実行することにする。
python -m pip uninstall -y tensorflow tensorflow-cpu tensorflow-gpu tensorflow_datasets tensorflow-hub keras python -m pip install -U tensorflow tensorflow_datasets numpy matplotlib seaborn scikit-learn scikit-learn-intelex
Windows でのインストール詳細(NVIDIA グラフィックスドライバ,NVIDIA CUDA ツールキット,NVIDIA cuDNN, TensorFlow 関連ソフトウエアを含む): 別ページで説明している.
端末で,次のコマンドを実行.
sudo pip3 uninstall -y tensorflow tensorflow-cpu tensorflow-gpu tensorflow_datasets tensorflow-hub keras sudo pip3 uninstall -y six wheel astunparse tensorflow-estimator numpy keras-preprocessing absl-py wrapt gast flatbuffers grpcio opt-einsum protobuf termcolor typing-extensions google-pasta h5py tensorboard-plugin-wit markdown werkzeug requests-oauthlib rsa cachetools google-auth google-auth-oauthlib tensorboard tensorflow sudo apt -y install python3-six python3-wheel python3-numpy python3-grpcio python3-protobuf python3-termcolor python3-typing-extensions python3-h5py python3-markdown python3-werkzeug python3-requests-oauthlib python3-rsa python3-cachetools python3-google-auth sudo apt -y install python3-numpy python3-sklearn python3-matplotlib python3-seaborn sudo pip3 install -U tensorflow tensorflow_datasets
Ubuntu でのインストール詳細(NVIDIA グラフィックスドライバ,NVIDIA CUDA ツールキット,NVIDIA cuDNN, TensorFlow 関連ソフトウエアを含む): 別ページで説明している.
sudo apt -y insatll graphviz python3-graphviz libgraphviz-dev
画像ファイル fruits.jpg, home.jpg のダウンロードは, Windows でコマンドプロンプトを管理者として実行し, 次のコマンドを実行.
mkdir c:\image cd c:\image curl -L https://github.com/opencv/opencv/blob/master/samples/data/fruits.jpg?raw=true -o fruits.jpg curl -L https://github.com/opencv/opencv/blob/master/samples/data/home.jpg?raw=true -o home.jpg
上のコマンドがうまく
https://github.com/opencv/opencv/tree/master/samples/data
で公開されている fruits.jpg, home.jpg を使用する(謝辞:画像の作者に感謝します)
参考 Web ページ: https://keras.io/ja/applications/
謝辞:ここでは、https://keras.io/ja/applications に記載のプログラムを変更して使用している
次の Python プログラムを実行
「C:/image/fruits.jpg」,
「C:/image/home.jpg」のところには,画像ファイル名を指定すること.
参考 Web ページ: https://keras.io/ja/applications/
謝辞:ここでは、https://keras.io/ja/applications に記載のプログラムを変更して使用している
「C:/image/fruits.jpg」,
「C:/image/home.jpg」のところには,画像ファイル名を指定すること.
参考 Web ページ: https://keras.io/ja/applications/
謝辞:ここでは、https://keras.io/ja/applications に記載のプログラムを変更して使用している
次の Python プログラムを実行
「C:/image/fruits.jpg」,
「C:/image/home.jpg」のところには,画像ファイル名を指定すること.
参考 Web ページ: https://keras.io/ja/applications/
謝辞:ここでは、https://keras.io/ja/applications に記載のプログラムを変更して使用している
次の Python プログラムを実行
「C:/image/fruits.jpg」,
「C:/image/home.jpg」のところには,画像ファイル名を指定すること.
参考 Web ページ: https://keras.io/ja/applications/
謝辞:ここでは、https://keras.io/ja/applications に記載のプログラムを変更して使用している
次の Python プログラムを実行
「C:/image/fruits.jpg」,
「C:/image/home.jpg」のところには,画像ファイル名を指定すること.
参考 Web ページ: https://keras.io/ja/applications/
謝辞:ここでは、https://keras.io/ja/applications に記載のプログラムを変更して使用している
次の Python プログラムを実行
「C:/image/fruits.jpg」,
「C:/image/home.jpg」のところには,画像ファイル名を指定すること.
4. ImageNet で学習済みの MobileNetV2 を用いた画像分類
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds
from tensorflow.keras.preprocessing import image
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore') # Suppress Matplotlib warnings
tf.enable_v2_behavior()
from tensorflow.keras import backend as K
K.clear_session()
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input, decode_predictions
IMG_SIZE = 224
m = MobileNetV2(weights='imagenet')
m.summary()
from tensorflow.keras.utils import plot_model
import pydot
plot_model(m)
from matplotlib import pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings('ignore') # Suppress Matplotlib warnings
import PIL
def preprocess_image(img_path, img_size):
img = image.load_img(img_path, target_size=(img_size, img_size))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
return preprocess_input(x)
def plot_image(img_path, img_size):
img = image.load_img(img_path, target_size=(img_size, img_size))
plt.imshow(img)
return
img_path = 'C:/image/fruits.jpg'
plot_image(img_path, IMG_SIZE)
print('Predicted:', decode_predictions(m.predict(preprocess_image(img_path, IMG_SIZE)), top=3)[0])
img_path = 'C:/image/home.jpg'
plot_image(img_path, IMG_SIZE)
print('Predicted:', decode_predictions(m.predict(preprocess_image(img_path, IMG_SIZE)), top=3)[0])
5. ImageNet で学習済みの ResNet50 を用いた画像分類
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np
IMG_SIZE = 224
m = ResNet50(weights='imagenet')
m.summary()
from tensorflow.keras.utils import plot_model
import pydot
plot_model(m)
from matplotlib import pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings('ignore') # Suppress Matplotlib warnings
import PIL
def preprocess_image(img_path, img_size):
img = image.load_img(img_path, target_size=(img_size, img_size))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
return preprocess_input(x)
def plot_image(img_path, img_size):
img = image.load_img(img_path, target_size=(img_size, img_size))
plt.imshow(img)
return
img_path = 'C:/image/fruits.jpg'
plot_image(img_path, IMG_SIZE)
print('Predicted:', decode_predictions(m.predict(preprocess_image(img_path, IMG_SIZE)), top=3)[0])
img_path = 'C:/image/home.jpg'
plot_image(img_path, IMG_SIZE)
print('Predicted:', decode_predictions(m.predict(preprocess_image(img_path, IMG_SIZE)), top=3)[0])
6. ImageNet で学習済みの Inception-ResNet を用いた画像分類
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds
from tensorflow.keras.applications.inception_resnet_v2 import InceptionResNetV2
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.inception_resnet_v2 import preprocess_input, decode_predictions
import numpy as np
IMG_SIZE = 299
m = InceptionResNetV2(weights='imagenet')
m.summary()
from tensorflow.keras.utils import plot_model
import pydot
plot_model(m)
from matplotlib import pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings('ignore') # Suppress Matplotlib warnings
import PIL
def preprocess_image(img_path, img_size):
img = image.load_img(img_path, target_size=(img_size, img_size))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
return preprocess_input(x)
def plot_image(img_path, img_size):
img = image.load_img(img_path, target_size=(img_size, img_size))
plt.imshow(img)
return
img_path = 'C:/image/fruits.jpg'
plot_image(img_path, IMG_SIZE)
print('Predicted:', decode_predictions(m.predict(preprocess_image(img_path, IMG_SIZE)), top=3)[0])
img_path = 'C:/image/home.jpg'
plot_image(img_path, IMG_SIZE)
print('Predicted:', decode_predictions(m.predict(preprocess_image(img_path, IMG_SIZE)), top=3)[0])
7. ImageNet で学習済みの DenseNet 121 を用いた画像分類
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds
from tensorflow.keras.applications.densenet import DenseNet121
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.densenet import preprocess_input, decode_predictions
import numpy as np
IMG_SIZE = 224
m = DenseNet121(weights='imagenet')
m.summary()
from tensorflow.keras.utils import plot_model
import pydot
plot_model(m)
from matplotlib import pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings('ignore') # Suppress Matplotlib warnings
import PIL
def preprocess_image(img_path, img_size):
img = image.load_img(img_path, target_size=(img_size, img_size))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
return preprocess_input(x)
def plot_image(img_path, img_size):
img = image.load_img(img_path, target_size=(img_size, img_size))
plt.imshow(img)
return
img_path = 'C:/image/fruits.jpg'
plot_image(img_path, IMG_SIZE)
print('Predicted:', decode_predictions(m.predict(preprocess_image(img_path, IMG_SIZE)), top=3)[0])
img_path = 'C:/image/home.jpg'
plot_image(img_path, IMG_SIZE)
print('Predicted:', decode_predictions(m.predict(preprocess_image(img_path, IMG_SIZE)), top=3)[0])
8. ImageNet で学習済みの DenseNet 169 を用いた画像分類
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds
from tensorflow.keras.applications.densenet import DenseNet169
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.densenet import preprocess_input, decode_predictions
import numpy as np
IMG_SIZE = 224
m = DenseNet169(weights='imagenet')
m.summary()
from tensorflow.keras.utils import plot_model
import pydot
plot_model(m)
from matplotlib import pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings('ignore') # Suppress Matplotlib warnings
import PIL
def preprocess_image(img_path, img_size):
img = image.load_img(img_path, target_size=(img_size, img_size))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
return preprocess_input(x)
def plot_image(img_path, img_size):
img = image.load_img(img_path, target_size=(img_size, img_size))
plt.imshow(img)
return
img_path = 'C:/image/fruits.jpg'
plot_image(img_path, IMG_SIZE)
print('Predicted:', decode_predictions(m.predict(preprocess_image(img_path, IMG_SIZE)), top=3)[0])
img_path = 'C:/image/home.jpg'
plot_image(img_path, IMG_SIZE)
print('Predicted:', decode_predictions(m.predict(preprocess_image(img_path, IMG_SIZE)), top=3)[0])
9. ImageNet で学習済みの NASNet Large を用いた画像分類
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds
from tensorflow.keras.applications.nasnet import NASNetLarge
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.nasnet import preprocess_input, decode_predictions
import numpy as np
IMG_SIZE = 331
m = NASNetLarge(weights='imagenet')
m.summary()
from tensorflow.keras.utils import plot_model
import pydot
plot_model(m)
from matplotlib import pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings('ignore') # Suppress Matplotlib warnings
import PIL
def preprocess_image(img_path, img_size):
img = image.load_img(img_path, target_size=(img_size, img_size))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
return preprocess_input(x)
def plot_image(img_path, img_size):
img = image.load_img(img_path, target_size=(img_size, img_size))
plt.imshow(img)
return
img_path = 'C:/image/fruits.jpg'
plot_image(img_path, IMG_SIZE)
print('Predicted:', decode_predictions(m.predict(preprocess_image(img_path, IMG_SIZE)), top=3)[0])
img_path = 'C:/image/home.jpg'
plot_image(img_path, IMG_SIZE)
print('Predicted:', decode_predictions(m.predict(preprocess_image(img_path, IMG_SIZE)), top=3)[0])