目次
URL: https://github.com/pierluigiferrari/ssd_keras
手順の要点: Python 3.6, TensorFlow 1.15, Python の隔離された環境(Windows では C:\venv\tf115py36)
ソフトウエア等の利用条件等は,利用者で確認すること.
謝辞:ソフトウエアの作者に感謝します.
TensorFlow 1.15 を使う.
「Visual Studio Community 2019 vesion 16.2, マイクロソフト C++ ビルドツールのインストール(Windows 上)」で説明している.
すでに TensorFlow 2 を使っている,あるいは使う予定ということがありえる. 単純には,TensorFlow 2 と TensorFlow 1.15 を共存させて Python で使うということはできないが, 少しの手間で,共存できるようになる. そこで,TensorFlow 2 とTensorFlow 1.15 の共存を前提として, TensorFlow 1.15 のインストールを行う.
【Python 開発環境のインストール】
Python を使うときは,Python開発環境や Python コンソール(Jupyter Qt Console,Spyder,PyCharm,PyScripter など)の利用も便利である
Windows, Ubuntu での Python 開発環境,Python コンソール(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, spyder)のインストール: 別ページで,インストール手順を説明している.
Windows でのPython3.6,TensorFlow 1.15 のインストール:別ページで説明している.
すでにPython 3.9 あるいは Python 3.8 をインストールしている,あるいは,インストール予定という場合を想定し, あとのトラブルが起きにくい,そして,簡単に運用できるように 「Python 3.6 をインストールし,その上に,TensorFlow 1.15.5 をインストールする」という手順を案内している.
Ubuntu でのPython,TensorFlow 1.15 のインストール:別ページで案内している.
Ubuntu のシステム Python に影響を与えないように,隔離された Python 3.6 仮想環境の新規作成し,その上にTensorFlow 1.15.5 をインストールするという手順(venv を使用)(Ubuntu 上)を案内している.
Git の URL: https://git-scm.com/
端末で,次のコマンドを実行
sudo apt -y update sudo apt -y install git
Windows での手順を下に示す.Ubuntu でも同様の手順になる.
python -m pip install -U numpy imageio tqdm beautifulsoup4 scikit-learn
cd c:\pytools 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 でも同様の手順になる.
cd c:\pytools\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)
※ 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 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})