目次
入力画像の例
出力としては「種類」を表すラベル(下の図では「Person」や「Bicycle」)と、バウンディングボックス
URL: https://github.com/SnowMasaya/ssd_keras
手順の要点: Python 3.6, TensorFlow 1.15, Python の仮想環境(Windows では C:\venv\tf115py36)
ソフトウエア等の利用条件等は,利用者で確認すること.
謝辞:ソフトウエアの作者に感謝します.
※ TensorFlow 1.15.3 に対応する Python は,3.6 や 3.7 など(3.8 は対応していない)(2020/06 時点).このページでは 3.6 を使って説明する.3.7 でも同様の手順になる.
Python の URL: http://www.python.org/
インストール手順の詳細は: 別ページで説明している.
コマンドプロンプトを管理者として実行し,次のコマンドを実行.
py -3.6 -m pip install -U pip setuptools
次の手順により,システム Python とは別に,pyenv を用いて Pytnon 3.6 をインストールする.(システム Python の設定は変えたくないため).
図などの入った詳しい説明は別ページ.
sudo apt -y install --no-install-recommends make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev cd /tmp curl https://pyenv.run | bash echo 'export PYENV_ROOT="${HOME}/.pyenv"' >> ~/.bashrc echo 'if [ -d "${PYENV_ROOT}" ]; then' >> ~/.bashrc echo ' export PATH=${PYENV_ROOT}/bin:$PATH' >> ~/.bashrc echo ' eval "$(pyenv init -)"' >> ~/.bashrc echo ' eval "$(pyenv virtualenv-init -)"' >> ~/.bashrc echo 'fi' >> ~/.bashrc exec $SHELL -l
pyenv install 3.6.10
端末で,次のコマンドを実行.
pyenv shell 3.6.10 python -m pip install -U pip setuptools
Git の URL: https://git-scm.com/
sudo apt -y install git
「Visual Studio Community 2019 vesion 16.2, Visual C++ ビルドツールのインストール(Windows 上)」で説明している.
以下,Windows に Python, git, Visual C++ ビルドツール (Build Tools) をインストール済みであるものとして説明を続ける.
※ GPU とは,グラフィックス・プロセッシング・ユニットの略で、コンピュータグラフィックス関連の機能,乗算や加算の並列処理の機能などがある.
ダウンロードページ
詳細説明
※ CUDA とは,NVIDIA社が提供している GPU 用のプラットフォームである. ダウンロードページ
指定されているバージョンより高いものは使わない. その根拠は次のページ. URL: https://www.tensorflow.org/install/source#common_installation_problems
詳細説明
ダウンロードページ
ダウンロードして展開(解凍)したら,パスを通しておくこと.
TensorFlow 2.4 の GPU 版での,cuDNN のバージョンは 8.0.5(現時点で,NVIDIA CUDA ツールキット 11.0 で動く最新版).
TensorFlow 2.3, 2.2, 2.1 の GPU 版での,cuDNN のバージョンは 7.6.そして,TensorFlow 1.13 以上 TensorFlow 2.0 までの GPU 版での,cuDNN のバージョンは7.4 .それより高いバージョンよりは使わないこと.
詳細説明
最新版ではない TensorFlow を使う.そうした場合,運用を簡単にする(バージョン指定のもの間違ってアップデートしないなど)のために,venv を用いて,隔離された Python 仮想環境を作る.
今から作成する隔離された Python 仮想環境の名前と、Pythonのバージョンを決めておく
ここで行う「隔離された Python 仮想環境の新規作成と,TensorFlow 1.15.3(旧バージョン)のインストール」ついては,より詳しくは,次のページで説明している.
Windows での Python 3.6 の準備は,このページの上の方で説明している.
下の例では,隔離された Python 仮想環境のためのディレクトリを C:\venv\tf115py36に作成している.
py -3.6 -m venv C:\venv\tf115py36
venv を使い,孤立した Python 仮想環境を使っているときは,Windows でも Ubuntu でも同じで,「python -m pip install ...」. いま,venv を使っているかどうかは,プロンプトの「(venv)」で分かる.
C:\venv\tf115py36\Scripts\activate.bat python -m pip install -U pip setuptools python -m pip install -U tensorflow-gpu==1.15.3 tensorflow_datasets python -m pip install -U jupyterlab jupyter jupyter-console jupytext nteract_on_jupyter spyder
Ubuntu での Python 3.6 の準備は,このページの上の方で説明している.
下の例では,隔離された Python 仮想環境のためのディレクトリを ~/tf115py36に作成している.
pyenv shell 3.6.10 python -m venv ~/tf115py36
venv を使い,孤立した Python 仮想環境を使っているときは,Windows でも Ubuntu でも同じで,「python -m pip install ...」. いま,venv を使っているかどうかは,プロンプトの「(venv)」で分かる.
source ~/tf115py36/bin/activate python -m pip install -U pip setuptools python -m pip install -U tensorflow-gpu==1.15.3 tensorflow_datasets python -m pip install -U jupyterlab jupyter jupyter-console jupytext nteract_on_jupyter spyder
※ バージョン番号が表示されれば OK.下の図とは違うバージョンが表示されることがある.
python -c "import tensorflow as tf; print( tf.__version__ )"
TensorFlow が GPU を認識できているかの確認は,端末で,次を実行して行う.
python -c "from tensorflow.python.client import device_lib; print(device_lib.list_local_devices())"
Windows での手順を下に示す.Ubuntu でも同様の手順になる.
※ 以下,Windows での手順を示す.Ubuntu でも同様の手順になる.
venv を使い,孤立した Python 仮想環境を使っているときは,Windows でも Ubuntu でも同じで,「python -m pip install ...」. いま,venv を使っているかどうかは,プロンプトの「(venv)」で分かる.
python -m pip install -U keras==2.0.9 matplotlib numpy imageio python -m pip install -U jupyterlab jupyter jupyter-console jupytext spyder
cd C:\venv\tf115py36 rmdir /s /q ssd_keras
git clone https://github.com/SnowMasaya/ssd_keras
下の図のように
Python コンソールで,SSD.ipynb に記載のコマンドを実行しながら結果を確認したい.結果は,画像などでプロットされる場合がある.
Windows での手順を下に示す.Ubuntu でも同様の手順になる.
※ 以下,Windows での手順を示す.Ubuntu でも同様の手順になる.
cd C:\venv\tf115py36\ssd_keras
jupyter qtconsole
Python プログラムを動かして,結果を見たい.
Jupyter Qt Console, spyder, PyCharm, PyScripter が便利である. Windows では,スタートメニューの「IDLE (Python ...)」も便利である.
※ 「jupyter qtconsole」を入れたのに,jupyter qtconsole が起動しない という場合には,次の操作で,インストールを行ってから,もう一度試してみる.
python -m pip install -U jupyterlab jupyter jupyter-console jupytext spyder
ここから先は,jupyter qtconsole の画面で説明する.
次を実行.「1024」のところは,適切に調整すること.
https://www.tensorflow.org/guide/gpu に記載の手順による.
from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf gpus = tf.config.experimental.list_physical_devices('GPU') if gpus: # Restrict TensorFlow to only allocate 1GB of memory on the first GPU try: tf.config.experimental.set_virtual_device_configuration( gpus[0], [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)]) logical_gpus = tf.config.experimental.list_logical_devices('GPU') print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs") except RuntimeError as e: # Virtual devices must be set before GPUs have been initialized print(e)
次の Python プログラムを実行
※ https://github.com/SnowMasaya/ssd_keras/blob/master/SSD.ipynb の「in [1]」に記載の通り.
from __future__ import absolute_import, division, print_function, unicode_literals from keras.applications.imagenet_utils import preprocess_input from keras.backend.tensorflow_backend import set_session from tensorflow.keras.preprocessing import image import matplotlib.pyplot as plt import numpy as np from imageio import imread import tensorflow as tf from ssd_v2 import SSD300v2 from ssd_utils import BBoxUtility import os plt.rcParams['figure.figsize'] = (8, 8) plt.rcParams['image.interpolation'] = 'nearest' np.set_printoptions(suppress=True)
次のようなエラーが出たときは, 「sys.path.append("C:\venv\tf115py36\ssd_keras")」のようなコマンドを実行の後,やり直す.
次の Python プログラムを実行
※ https://github.com/SnowMasaya/ssd_keras/blob/master/SSD.ipynb の「in [2]」に記載の通り.
voc_classes = ['Aeroplane', 'Bicycle', 'Bird', 'Boat', 'Bottle', 'Bus', 'Car', 'Cat', 'Chair', 'Cow', 'Diningtable', 'Dog', 'Horse','Motorbike', 'Person', 'Pottedplant', 'Sheep', 'Sofa', 'Train', 'Tvmonitor'] NUM_CLASSES = len(voc_classes) + 1
次の Python プログラムを実行
※ https://github.com/SnowMasaya/ssd_keras/blob/master/SSD.ipynb の「in [3]」に記載の通り.
input_shape=(300, 300, 3) model = SSD300v2(input_shape, num_classes=NUM_CLASSES) model.load_weights('weights_SSD300.hdf5', by_name=True) bbox_util = BBoxUtility(NUM_CLASSES)
次の Python プログラムを実行
※ https://github.com/rykov8/ssd_keras/blob/master/SSD.ipynb の「in [4]」に記載の通り.
inputs = [] images = [] img_path = './pics/fish-bike.jpg' img = image.load_img(img_path, target_size=(300, 300)) img = image.img_to_array(img) images.append(imread(img_path)) inputs.append(img.copy()) img_path = './pics/cat.jpg' img = image.load_img(img_path, target_size=(300, 300)) img = image.img_to_array(img) images.append(imread(img_path)) inputs.append(img.copy()) img_path = './pics/boys.jpg' img = image.load_img(img_path, target_size=(300, 300)) img = image.img_to_array(img) images.append(imread(img_path)) inputs.append(img.copy()) img_path = './pics/car_cat.jpg' img = image.load_img(img_path, target_size=(300, 300)) img = image.img_to_array(img) images.append(imread(img_path)) inputs.append(img.copy()) img_path = './pics/car_cat2.jpg' img = image.load_img(img_path, target_size=(300, 300)) img = image.img_to_array(img) images.append(imread(img_path)) inputs.append(img.copy()) inputs = preprocess_input(np.array(inputs))
次の Python プログラムを実行
※ https://github.com/rykov8/ssd_keras/blob/master/SSD.ipynb の「in [5]」に記載の通り.
preds = model.predict(inputs, batch_size=1, verbose=1)
次の Python プログラムを実行
※ https://github.com/rykov8/ssd_keras/blob/master/SSD.ipynb の「in [6]」に記載の通り.
results = bbox_util.detection_out(preds)
次の Python プログラムを実行
※ https://github.com/rykov8/ssd_keras/blob/master/SSD.ipynb の「in [8]」に記載の通り.
for i, img in enumerate(images): # Parse the outputs. det_label = results[i][:, 0] det_conf = results[i][:, 1] det_xmin = results[i][:, 2] det_ymin = results[i][:, 3] det_xmax = results[i][:, 4] det_ymax = results[i][:, 5] # Get detections with confidence higher than 0.6. top_indices = [i for i, conf in enumerate(det_conf) if conf >= 0.6] top_conf = det_conf[top_indices] top_label_indices = det_label[top_indices].tolist() top_xmin = det_xmin[top_indices] top_ymin = det_ymin[top_indices] top_xmax = det_xmax[top_indices] top_ymax = det_ymax[top_indices] colors = plt.cm.hsv(np.linspace(0, 1, 21)).tolist() plt.figure() plt.imshow(img / 255.) currentAxis = plt.gca() for i in range(top_conf.shape[0]): xmin = int(round(top_xmin[i] * img.shape[1])) ymin = int(round(top_ymin[i] * img.shape[0])) xmax = int(round(top_xmax[i] * img.shape[1])) ymax = int(round(top_ymax[i] * img.shape[0])) score = top_conf[i] label = int(top_label_indices[i]) label_name = voc_classes[label - 1] display_txt = '{:0.2f}, {}'.format(score, label_name) coords = (xmin, ymin), xmax-xmin+1, ymax-ymin+1 color = colors[label] currentAxis.add_patch(plt.Rectangle(*coords, fill=False, edgecolor=color, linewidth=2)) currentAxis.text(xmin, ymin, display_txt, bbox={'facecolor':color, 'alpha':0.5}) plt.show()
実行結果
本サイトは金子邦彦研究室のWebページです.サイトマップは,サイトマップのページをご覧下さい. 本サイト内の検索は,サイト内検索のページをご利用下さい.
問い合わせ先: 金子邦彦(かねこ くにひこ)