SSD Keras の実装である rykov ssd_keras を使ってみる.
目次
URL: https://github.com/rykov8/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/
インストール手順の詳細は: 別ページで説明している.
Windows では,Python 3.8 や 3.6 の共存は簡単.
コマンドプロンプトを管理者として実行し,次のコマンドを実行.
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.12
端末で,次のコマンドを実行.
pyenv shell 3.6.12 python -m pip install -U pip setuptools python -m pip install -U jupyterlab jupyter jupyter-console jupytext nteract_on_jupyter spyder
osudo apt -y install git
※ 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 で動く最新版).
TensorFlow 2.3, 2.2, 2.1 の GPU 版での,cuDNN のバージョンは 7.6.そして,TensorFlow 1.13 以上 TensorFlow 2.0 までの GPU 版での,cuDNN のバージョンは7.4 .それより高いバージョンよりは使わないこと.
詳細説明
Python 3.6 を起動するコマンドを確認しておくこと.
C:\venv\tf115py36\Scripts\activate.bat
Python の使用は,隔離された Python 仮想環境の有効化の後,「python」で行う. Windows で,隔離された Python 仮想環境を使用しないときは,「python」ではなく「py -3.6」を使う.
python -m pip uninstall -y tensorflow tensorflow-cpu tensorflow-gpu tensorflow_datasets tensorflow-hub keras python -m pip install -U tensorflow==1.15.5 tensorflow_datasets tensorflow-hub keras==1.2.2 matplotlib opencv-python python -m pip install git+https://github.com/tensorflow/docs python -m pip install git+https://github.com/tensorflow/examples.git
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())"
端末で,次のコマンドを実行.
pyenv shell 3.6.12
隔離された Python 仮想環境を使用するときは, 「pyenv shell 3.6.12」は実行しないで, 次のようなコマンドで Python 仮想環境を有効化する.
source ~/tf115py36/bin/activate
Python の使用は,「python」で行う.
python -m pip uninstall -y tensorflow tensorflow-cpu tensorflow-gpu tensorflow_datasets tensorflow-hub keras python -m pip install -U tensorflow==1.15.5 tensorflow_datasets tensorflow-hub keras==1.2.2 matplotlib opencv-python python -m pip install git+https://github.com/tensorflow/docs python -m pip install git+https://github.com/tensorflow/examples.git
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 の場合での,有効化のコマンドの例.
C:\venv\tf115py36\Scripts\activate.bat
Ubuntu の場合での,有効化のコマンドの例.
source ~/tf115py36/bin/activate
※ 以下,Windows での手順を示す.Ubuntu でも同様の手順になる.
venv を使い,孤立した Python 仮想環境を使っているときは,Windows でも Ubuntu でも同じで,「python -m pip install ...」.
python -m pip install -U keras==1.2.2 matplotlib numpy imageio opencv-python 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/rykov8/ssd_keras
下の図のように
Python コンソールで,SSD.ipynb に記載のコマンドを実行しながら結果を確認したい.結果は,画像などでプロットされる場合がある.
Windows での手順を下に示す.Ubuntu でも同様の手順になる.
Windows の場合での,有効化のコマンドの例.
C:\venv\tf115py36\Scripts\activate.bat
Ubuntu の場合での,有効化のコマンドの例.
source ~/tf115py36/bin/activate
※ 以下,Windows での手順を示す.Ubuntu でも同様の手順になる.
cd C:\venv\tf115py36\ssd_keras
次を実行.「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/rykov8/ssd_keras/blob/master/SSD.ipynb の「in [1]」に記載の通り.
from __future__ import absolute_import, division, print_function, unicode_literals
import cv2
import keras
from keras.applications.imagenet_utils import preprocess_input
from keras.backend.tensorflow_backend import set_session
from keras.models import Model
from tensorflow.keras.preprocessing import image
import matplotlib.pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings('ignore') # Suppress Matplotlib warnings
import numpy as np
from imageio import imread
import tensorflow as tf
from ssd import SSD300
from ssd_utils import BBoxUtility
plt.rcParams['figure.figsize'] = (8, 8)
plt.rcParams['image.interpolation'] = 'nearest'
np.set_printoptions(suppress=True)
次の Python プログラムを実行
※ https://github.com/rykov8/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/rykov8/ssd_keras/blob/master/SSD.ipynb の「in [3]」に記載の通り.
input_shape=(300, 300, 3)
model = SSD300(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()
実行結果