TensorFlow Graphics : Beginner Tutorials : 物体ポーズ推定 / 整列 (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 05/25/2019
* 本ページは、TensorFlow Graphics の github レポジトリの次のページを翻訳した上で適宜、補足説明したものです:
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
TensorFlow Graphics : Beginner Tutorials : 物体ポーズ推定 / 整列
物体のポーズを正確に推定することは多くの業種 (= industries) で基本的です。例えば拡張現実と仮想現実において、これらのオブジェクトと相互作用することによりそれはユーザに幾つかの変数の状態を変更することを可能にします (e.g. ユーザのデスクの上のマグにより制御される容量)。
このノートブックは既知の 3D 物体の回転と移動を推定するために TensorFlow Graphics をどのように使用するかを示します。
この能力は 2 つの異なるデモにより示されます :
- 機械学習デモ、これは与えられた物体の参照ポーズに関する回転と移動を正確に見積もることができる単純なニューラルネットワークをどのように訓練するかを示します。
- 数学的最適化デモ、これはこの問題への異なるアプローチを取ります ; 機械学習は使用しません。
セットアップ & Imports
このノートブックに含まれるデモを実行するために必要な総てを import しましょう。
from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.math import vector from tensorflow_graphics.notebooks import threejs_visualization from tensorflow_graphics.notebooks.resources import tfg_simplified_logo tf.enable_eager_execution() # Loads the Tensorflow Graphics simplified logo. vertices = tfg_simplified_logo.mesh['vertices'].astype(np.float32) faces = tfg_simplified_logo.mesh['faces'] num_vertices = vertices.shape[0]
1. 機械学習
モデル定義
既知のメッシュの総ての頂点の 3D 位置が与えられたとき、参照ポーズに関するこのメッシュの (クォータニオン (4 次元ベクトル) によりパラメータ化された) 回転と移動 (3 次元ベクトル) を予測する能力があるネットワークを望みます。今、タスクのための非常に単純な 3-層完全結合ネットワークと損失を作成しましょう。このモデルは非常に単純で明らかに最善ではないことに注意してください、それはこのノートブックのためには範囲外です。
# モデルを構築する。 model = keras.Sequential() model.add(layers.Flatten(input_shape=(num_vertices, 3))) model.add(layers.Dense(64, activation=tf.nn.tanh)) model.add(layers.Dense(64, activation=tf.nn.relu)) model.add(layers.Dense(7)) def pose_estimation_loss(y_true, y_pred): """訓練のために使用されるポーズ推定損失。 This loss measures the average of squared distance between some vertices of the mesh in 'rest pose' and the transformed mesh to which the predicted inverse pose is applied. Comparing this loss with a regular L2 loss on the quaternion and translation values is left as exercise to the interested reader. Args: y_true: The ground-truth value. y_pred: The prediction we want to evaluate the loss for. Returns: A scalar value containing the loss described in the description above. """ # y_true.shape : (batch, 7) y_true_q, y_true_t = tf.split(y_true, (4, 3), axis=-1) # y_pred.shape : (batch, 7) y_pred_q, y_pred_t = tf.split(y_pred, (4, 3), axis=-1) # vertices.shape: (num_vertices, 3) # corners.shape:(num_vertices, 1, 3) corners = tf.expand_dims(vertices, axis=1) # transformed_corners.shape: (num_vertices, batch, 3) # q and t shapes get pre-pre-padded with 1's following standard broadcast rules. transformed_corners = quaternion.rotate(corners, y_pred_q) + y_pred_t # recovered_corners.shape: (num_vertices, batch, 3) recovered_corners = quaternion.rotate(transformed_corners - y_true_t, quaternion.inverse(y_true_q)) # vertex_error.shape: (num_vertices, batch) vertex_error = tf.reduce_sum((recovered_corners - corners)**2, axis=-1) return tf.reduce_mean(vertex_error) optimizer = keras.optimizers.Adam() model.compile(loss=pose_estimation_loss, optimizer=optimizer)
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= flatten (Flatten) (None, 114) 0 _________________________________________________________________ dense (Dense) (None, 64) 7360 _________________________________________________________________ dense_1 (Dense) (None, 64) 4160 _________________________________________________________________ dense_2 (Dense) (None, 7) 455 ================================================================= Total params: 11,975 Trainable params: 11,975 Non-trainable params: 0 _________________________________________________________________
データ生成
モデルを定義した今、それを訓練するためのデータが必要です。訓練セットの各サンプルについて、ランダムな 3D 回転と 3D 移動がサンプリングされて物体の頂点に適用されます。各訓練サンプルは総ての変換された頂点と (サンプルに適用された) 回転と移動を戻すことを可能にする反対の回転と移動から成ります。
def generate_training_data(num_samples): # random_angles.shape: (num_samples, 3) random_angles = np.random.uniform(-np.pi, np.pi, (num_samples, 3)).astype(np.float32) # random_quaternion.shape: (num_samples, 4) random_quaternion = quaternion.from_euler(random_angles) # random_translation.shape: (num_samples, 3) random_translation = np.random.uniform(-2.0, 2.0, (num_samples, 3)).astype(np.float32) # data.shape : (num_samples, num_vertices, 3) data = quaternion.rotate(vertices[tf.newaxis, :, :], random_quaternion[:, tf.newaxis, :] ) + random_translation[:, tf.newaxis, :] # target.shape : (num_samples, 4+3) target = tf.concat((random_quaternion, random_translation), axis=-1) return np.array(data), np.array(target)
num_samples = 10000 data, target = generate_training_data(num_samples) print(data.shape) # (num_samples, num_vertices, 3): the vertices print(target.shape) # (num_samples, 4+3): the quaternion and translation
(10000, 38, 3) (10000, 7)
訓練
この時点で、ニューラルネットワークの訓練を開始するために総てが適切です!
# Callback allowing to display the progression of the training task. class ProgressTracker(keras.callbacks.Callback): def __init__(self, num_epochs, step=5): self.num_epochs = num_epochs self.current_epoch = 0. self.step = step self.last_percentage_report = 0 def on_epoch_end(self, batch, logs={}): self.current_epoch += 1. training_percentage = int(self.current_epoch * 100.0 / self.num_epochs) if training_percentage - self.last_percentage_report >= self.step: print('Training ' + str( training_percentage) + '% complete. Training loss: ' + str( logs.get('loss')) + ' | Validation loss: ' + str( logs.get('val_loss'))) self.last_percentage_report = training_percentage
reduce_lr_callback = keras.callbacks.ReduceLROnPlateau( monitor='val_loss', factor=0.5, patience=10, verbose=0, mode='auto', min_delta=0.0001, cooldown=0, min_lr=0)
# Everything is now in place to train. EPOCHS = 100 pt = ProgressTracker(EPOCHS) history = model.fit( data, target, epochs=EPOCHS, validation_split=0.2, verbose=0, batch_size=32, callbacks=[reduce_lr_callback, pt]) plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.ylim([0, 1]) plt.legend(['loss', 'val loss'], loc='upper left') plt.xlabel('Train epoch') _ = plt.ylabel('Error [mean square distance]')
Training 5% complete. Training loss: 1.009950121998787 | Validation loss: 0.9137270336151123 Training 10% complete. Training loss: 0.5268501298427581 | Validation loss: 0.5240717251300812 Training 15% complete. Training loss: 0.3752533705532551 | Validation loss: 0.37031882667541505 Training 20% complete. Training loss: 0.29893275210261344 | Validation loss: 0.29115591061115265 Training 25% complete. Training loss: 0.24757031705975532 | Validation loss: 0.23939514791965485 Training 30% complete. Training loss: 0.22420285016298294 | Validation loss: 0.21258240276575088 Training 35% complete. Training loss: 0.19799123887717723 | Validation loss: 0.1807250078320503 Training 40% complete. Training loss: 0.17767862628400327 | Validation loss: 0.1784087748527527 Training 45% complete. Training loss: 0.17318876099586486 | Validation loss: 0.15155328786373137 Training 50% complete. Training loss: 0.15236466732621193 | Validation loss: 0.16674353015422821 Training 55% complete. Training loss: 0.13417977157235145 | Validation loss: 0.13277354818582535 Training 60% complete. Training loss: 0.15286476877331734 | Validation loss: 0.13142506104707719 Training 65% complete. Training loss: 0.13228631572425364 | Validation loss: 0.13619410294294357 Training 70% complete. Training loss: 0.1253597312271595 | Validation loss: 0.11984566831588746 Training 75% complete. Training loss: 0.08613634746521712 | Validation loss: 0.09534638980031014 Training 80% complete. Training loss: 0.07220880922675132 | Validation loss: 0.07457096055150032 Training 85% complete. Training loss: 0.07194197417795659 | Validation loss: 0.055152468413114546 Training 90% complete. Training loss: 0.06660718904435635 | Validation loss: 0.07816255846619606 Training 95% complete. Training loss: 0.07537854766100645 | Validation loss: 0.08529620145261288 Training 100% complete. Training loss: 0.04841766462475061 | Validation loss: 0.05356932772696018
テスティング
今ではネットワークは訓練されて利用する準備ができました!表示される結果は 2 つの画像から成ります。最初の画像は「静止ポーズ (= rest pose)」にある物体 (パステル・レモン色) と回転されて移動された物体 (パステル・ハニーデュー色) を含みます。これは 2 つの構成がどのように異なるかを観察することを効果的に可能にします。2 番目の画像はまた静止ポーズの物体を示しますが、今回は訓練されたニューラルネットワークにより予測された変換が回転されて移動されたバージョンに適用されます。望ましくは、2 つの物体が今では非常に類似したポーズであることです。
Note: 異なるテストケースをサンプリングするために複数回プレーを押してください。貴方は時々物体のスケーリングが無効であることに気付くでしょう。これはクォータニオンがスケールをエンコードできるという事実に由来します。単位ノルムのクォータニオンの使用は結果のスケールを変更しないという結果になるでしょう。ネットワーク・アーキテクチャか損失関数でこの制約を追加する実験を興味ある読者に委ねます。
クォータニオンと移動を適用するヘルパー関数から始めます :
# Defines the loss function to be optimized. def transform_points(target_points, quaternion_variable, translation_variable): return quaternion.rotate(target_points, quaternion_variable) + translation_variable
変換された形状のための threejs ビューアを定義します :
class Viewer(object): def __init__(self, my_vertices): my_vertices = np.asarray(my_vertices) context = threejs_visualization.build_context() light1 = context.THREE.PointLight.new_object(0x808080) light1.position.set(10., 10., 10.) light2 = context.THREE.AmbientLight.new_object(0x808080) lights = (light1, light2) material = context.THREE.MeshLambertMaterial.new_object({ 'color': 0xfffacd, }) material_deformed = context.THREE.MeshLambertMaterial.new_object({ 'color': 0xf0fff0, }) camera = threejs_visualization.build_perspective_camera( field_of_view=30, position=(10.0, 10.0, 10.0)) mesh = {'vertices': vertices, 'faces': faces, 'material': material} transformed_mesh = { 'vertices': my_vertices, 'faces': faces, 'material': material_deformed } geometries = threejs_visualization.triangular_mesh_renderer( [mesh, transformed_mesh], lights=lights, camera=camera, width=400, height=400) self.geometries = geometries def update(self, transformed_points): self.geometries[1].getAttribute('position').copyArray( transformed_points.numpy().ravel().tolist()) self.geometries[1].getAttribute('position').needsUpdate = True
ランダム回転と移動を定義します :
def get_random_transform(): # Forms a random translation with tf.name_scope('translation_variable'): random_translation = tf.Variable( np.random.uniform(-2.0, 2.0, (3,)), dtype=tf.float32) # Forms a random quaternion hi = np.pi lo = -hi random_angles = np.random.uniform(lo, hi, (3,)).astype(np.float32) with tf.name_scope('rotation_variable'): random_quaternion = tf.Variable(quaternion.from_euler(random_angles)) return random_quaternion, random_translation
変換パラメータを予測するモデルを実行して、結果を可視化します :
random_quaternion, random_translation = get_random_transform() initial_orientation = transform_points(vertices, random_quaternion, random_translation).numpy() viewer = Viewer(initial_orientation) predicted_transformation = model.predict(initial_orientation[tf.newaxis, :, :]) predicted_inverse_q = quaternion.inverse(predicted_transformation[0, 0:4]) predicted_inverse_t = -predicted_transformation[0, 4:] predicted_aligned = quaternion.rotate(initial_orientation + predicted_inverse_t, predicted_inverse_q) viewer = Viewer(predicted_aligned)
(訳注 : 幾つかの実行サンプルを以下に示します : )
2. 数学的最適化
ここでは問題は数学的最適化を使用して取り組まれます、これは物体ポーズ推定の問題にアプローチするためのもう一つの伝統的な方法です。「静止ポーズ」にある物体 (パステルレモン色) とその回転されて移動された対応物体 (パステルハニーデュー色) 間の対応が与えられたとき、問題は最小化問題として定式化できます。損失関数は例えば、変換された物体の回転と移動の現在の推定を使用して対応する点のユークリッド距離の総計として定義できます。そしてこの損失に関する回転と移動パラメータの導関数を計算して、収束まで勾配方向をフォローできます。次のセルはこの手続きを密接にフォローし、そして 2 つの物体を整列するために勾配効果を使用します。結果は良いですが、注目すべき点としてこの特定の問題を解くためにより効率的な方法があります。興味ある読者はより詳細について Kabsch アルゴリズムを参照してください。
損失と勾配関数を定義します :
def loss(target_points, quaternion_variable, translation_variable): transformed_points = transform_points(target_points, quaternion_variable, translation_variable) error = (vertices - transformed_points) / num_vertices return vector.dot(error, error) def gradient_loss(target_points, quaternion, translation): with tf.GradientTape() as tape: loss_value = loss(target_points, quaternion, translation) return tape.gradient(loss_value, [quaternion, translation])
optimizer を作成します。
learning_rate = 0.05 with tf.name_scope('optimization'): optimizer = tf.train.AdamOptimizer(learning_rate)
ランダム変換を初期化して、最適化を実行して結果をアニメーションにします。
random_quaternion, random_translation = get_random_transform() transformed_points = transform_points(vertices, random_quaternion, random_translation) viewer = Viewer(transformed_points) nb_iterations = 100 for it in range(nb_iterations): gradients_loss = gradient_loss(vertices, random_quaternion, random_translation) optimizer.apply_gradients( zip(gradients_loss, (random_quaternion, random_translation))) transformed_points = transform_points(vertices, random_quaternion, random_translation) viewer.update(transformed_points) time.sleep(0.1)
以上