目次
URL: https://github.com/pierluigiferrari/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 python -m pip install -U jupyterlab jupyter jupyter-console jupytext nteract_on_jupyter spyder
sudo 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.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
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
※ バージョン番号が表示されれば 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.2.4 opencv-python matplotlib numpy imageio tqdm beautifulsoup4 scikit-learn 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/pierluigiferrari/ssd_keras
参考Webページ: https://github.com/pierluigiferrari/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 Qt Console の画面で説明する.
次を実行.「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)
※ https://github.com/pierluigiferrari/ssd_keras/blob/master/ssd512_inference.ipynbによる
次の Python プログラムを実行
from __future__ import absolute_import, division, print_function, unicode_literals from keras import backend as K from keras.models import load_model from tensorflow.keras.preprocessing import image from keras.optimizers import Adam from imageio import imread import numpy as np from matplotlib import pyplot as plt from models.keras_ssd512 import ssd_512 from keras_loss_function.keras_ssd_loss import SSDLoss from keras_layers.keras_layer_AnchorBoxes import AnchorBoxes from keras_layers.keras_layer_DecodeDetections import DecodeDetections from keras_layers.keras_layer_DecodeDetectionsFast import DecodeDetectionsFast from keras_layers.keras_layer_L2Normalization import L2Normalization from ssd_encoder_decoder.ssd_output_decoder import decode_detections, decode_detections_fast from data_generator.object_detection_2d_data_generator import DataGenerator from data_generator.object_detection_2d_photometric_ops import ConvertTo3Channels from data_generator.object_detection_2d_geometric_ops import Resize from data_generator.object_detection_2d_misc_utils import apply_inverse_transforms
※ https://github.com/pierluigiferrari/ssd_keras/blob/master/ssd512_inference.ipynbによる
次の Python プログラムを実行
# Set the image size. img_height = 512 img_width = 512
※ https://github.com/pierluigiferrari/ssd_keras/blob/master/ssd512_inference.ipynbによる
次の Python プログラムを実行
# 1: Build the Keras model K.clear_session() # Clear previous models from memory. m = ssd_512(image_size=(img_height, img_width, 3), n_classes=20, mode='inference', l2_regularization=0.0005, scales=[0.07, 0.15, 0.3, 0.45, 0.6, 0.75, 0.9, 1.05], # The scales for MS COCO are [0.04, 0.1, 0.26, 0.42, 0.58, 0.74, 0.9, 1.06] aspect_ratios_per_layer=[[1.0, 2.0, 0.5], [1.0, 2.0, 0.5, 3.0, 1.0/3.0], [1.0, 2.0, 0.5, 3.0, 1.0/3.0], [1.0, 2.0, 0.5, 3.0, 1.0/3.0], [1.0, 2.0, 0.5, 3.0, 1.0/3.0], [1.0, 2.0, 0.5], [1.0, 2.0, 0.5]], two_boxes_for_ar1=True, steps=[8, 16, 32, 64, 128, 256, 512], offsets=[0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5], clip_boxes=False, variances=[0.1, 0.1, 0.2, 0.2], normalize_coords=True, subtract_mean=[123, 117, 104], swap_channels=[2, 1, 0], confidence_thresh=0.5, iou_threshold=0.45, top_k=200, nms_max_output_size=400) # 2: Load the trained weights into the model. # TODO: Set the path of the trained weights. weights_path = 'VGG_VOC0712_SSD_512x512_iter_120000.h5' m.load_weights(weights_path, by_name=True) # 3: Compile the model so that Keras won't complain the next time you load it. adam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0) ssd_loss = SSDLoss(neg_pos_ratio=3, alpha=1.0) m.compile(optimizer=adam, loss=ssd_loss.compute_loss)
※ https://github.com/pierluigiferrari/ssd_keras/blob/master/ssd512_inference.ipynbによる
次の Python プログラムを実行
orig_images = [] # Store the images here. input_images = [] # Store resized versions of the images here. # We'll only load one image in this example. img_path = 'examples/fish_bike.jpg' orig_images.append(imread(img_path)) img = image.load_img(img_path, target_size=(img_height, img_width)) img = image.img_to_array(img) input_images.append(img) input_images = np.array(input_images)
※ https://github.com/pierluigiferrari/ssd_keras/blob/master/ssd512_inference.ipynbによる
次の Python プログラムを実行
y_pred = m.predict(input_images)
※ https://github.com/pierluigiferrari/ssd_keras/blob/master/ssd512_inference.ipynbによる
次の Python プログラムを実行
confidence_threshold = 0.5 y_pred_thresh = [y_pred[k][y_pred[k,:,1] > confidence_threshold] for k in range(y_pred.shape[0])] np.set_printoptions(precision=2, suppress=True, linewidth=90) print("Predicted boxes:\n") print(' class conf xmin ymin xmax ymax') print(y_pred_thresh[0])
※ https://github.com/pierluigiferrari/ssd_keras/blob/master/ssd512_inference.ipynbによる
次の Python プログラムを実行
# Display the image and draw the predicted boxes onto it. # Set the colors for the bounding boxes colors = plt.cm.hsv(np.linspace(0, 1, 21)).tolist() classes = ['background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'] plt.figure(figsize=(20,12)) plt.imshow(orig_images[0]) current_axis = plt.gca() for box in y_pred_thresh[0]: # Transform the predicted bounding boxes for the 512x512 image to the original image dimensions. xmin = box[-4] * orig_images[0].shape[1] / img_width ymin = box[-3] * orig_images[0].shape[0] / img_height xmax = box[-2] * orig_images[0].shape[1] / img_width ymax = box[-1] * orig_images[0].shape[0] / img_height color = colors[int(box[0])] label = '{}: {:.2f}'.format(classes[int(box[0])], box[1]) current_axis.add_patch(plt.Rectangle((xmin, ymin), xmax-xmin, ymax-ymin, color=color, fill=False, linewidth=2)) current_axis.text(xmin, ymin, label, size='x-large', color='white', bbox={'facecolor':color, 'alpha':1.0})
本サイトは金子邦彦研究室のWebページです.サイトマップは,サイトマップのページをご覧下さい. 本サイト内の検索は,サイト内検索のページをご利用下さい.
問い合わせ先: 金子邦彦(かねこ くにひこ)