本日はUnityの技術調査枠です。
Unity AIのドキュメントを読みながら実際に操作を試して記事に残します。
Unity AI
以下のUnity AIのドキュメントを試しながら実行時のキャプチャをしていきます。
docs.unity3d.com
ワークフローの例
ここでの例は推論エンジンの基本的なワークフローを示しています。
手書きの数字の画像を取得し、その画像が数字を表す可能性を予測する簡単なスクリプトが含まれています。
ワークフロー例を使用する
ワークフロー例を使用するには以下の手順を実施します。
シーン内のゲームオブジェクトに以下のスクリプトをアタッチします。
using UnityEngine; using Unity.InferenceEngine; public class ClassifyHandwrittenDigit : MonoBehaviour { public Texture2D inputTexture; public ModelAsset modelAsset; Model runtimeModel; Worker worker; public float[] results; void Start() { Model sourceModel = ModelLoader.Load(modelAsset); // Create a functional graph that runs the input model and then applies softmax to the output. FunctionalGraph graph = new FunctionalGraph(); FunctionalTensor[] inputs = graph.AddInputs(sourceModel); FunctionalTensor[] outputs = Functional.Forward(sourceModel, inputs); FunctionalTensor softmax = Functional.Softmax(outputs[0]); // Create a model with softmax by compiling the functional graph. graph.AddOutput(softmax); runtimeModel = graph.Compile(); // Create input data as a tensor using Tensor<float> inputTensor = new Tensor<float>(new TensorShape(1, 1, 28, 28)); TextureConverter.ToTensor(inputTexture, inputTensor); // Create an engine worker = new Worker(runtimeModel, BackendType.GPUCompute); // Run the model with the input data worker.Schedule(inputTensor); // Get the result Tensor<float> outputTensor = worker.PeekOutput() as Tensor<float>; // outputTensor is still pending // Either read back the results asynchronously or do a blocking download call results = outputTensor.DownloadToArray(); } void OnDisable() { // Tell the GPU we're finished with the memory the engine used worker.Dispose(); } }

ONNX Model Zoo(GitHub)から手書き認識ONNXモデルファイルをダウンロードします。
例えばMNIST手書き数字認識モデルmnist-8.onnxなどです。
・ONNX Model Zoo(GitHub)
github.com
・手書き数字認識モデル
github.com

ダウンロードしたモデルファイルをプロジェクトウィンドウのAssetsフォルダにドラッグします。

ゲームオブジェクトのInspectorウィンドウを開き、モデルアセットを[modelAsset]フィールドにドラッグします。

以下の画像をサンプルに利用します。

プロジェクトウィンドウのAssetsフォルダにサンプル画像をドラッグしてインポートします。

インポートした画像のInspectorウィンドウを開き、[Non-Power of 2]を[None]に設定して[Apply]を選択します。
本項目は縦横のサイズが2の累乗でないテクスチャを自動で2の累乗にリサイズするかを設定する項目です。

ゲームオブジェクトのInspectorウィンドウを開き、画像アセットを[inputTexture]フィールドにドラッグします。

シーンを再生してプロジェクトを実行します。

ゲームオブジェクトのInspectorウィンドウではResults配列の各項目はモデルが画像を数字であると予測した確率を示しています。
例えば、配列の項目7はモデルが画像を手書きの7であると予測した確率を表しています。
