|
using System.Collections.Generic; |
|
using Unity.Sentis; |
|
using UnityEngine; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public class RunMobileNet : MonoBehaviour |
|
{ |
|
const string modelName = "mobilenet_v2.sentis"; |
|
|
|
|
|
public Texture2D inputImage; |
|
|
|
|
|
public TextAsset labelsAsset; |
|
|
|
|
|
const int imageHeight = 224; |
|
const int imageWidth = 224; |
|
|
|
const BackendType backend = BackendType.GPUCompute; |
|
private Model model; |
|
private IWorker engine; |
|
private string[] labels; |
|
|
|
static Ops ops; |
|
ITensorAllocator allocator; |
|
|
|
void Start() |
|
{ |
|
|
|
allocator = new TensorCachingAllocator(); |
|
ops = WorkerFactory.CreateOps(backend, allocator); |
|
|
|
|
|
labels = labelsAsset.text.Split('\n'); |
|
|
|
|
|
model = ModelLoader.Load(Application.streamingAssetsPath + "/" + modelName); |
|
|
|
|
|
engine = WorkerFactory.CreateWorker(backend, model); |
|
|
|
|
|
ExecuteML(); |
|
} |
|
|
|
public void ExecuteML() |
|
{ |
|
|
|
using var rawinput = TextureConverter.ToTensor(inputImage, 224, 224, 3); |
|
using var input = Normalise(rawinput); |
|
|
|
|
|
engine.Execute(input); |
|
|
|
|
|
var output = engine.PeekOutput() as TensorFloat; |
|
var argmax = ops.ArgMax(output, 1, false); |
|
argmax.MakeReadable(); |
|
|
|
|
|
var res = argmax[0]; |
|
var label = labels[res]; |
|
|
|
output.MakeReadable(); |
|
var accuracy = output[res]; |
|
|
|
|
|
int percent = Mathf.FloorToInt(accuracy * 100f + 0.5f); |
|
Debug.Log($"{label} {percent}﹪"); |
|
|
|
|
|
Resources.UnloadUnusedAssets(); |
|
} |
|
|
|
|
|
TensorFloat Normalise(TensorFloat image) |
|
{ |
|
using var M = new TensorFloat(new TensorShape(1, 3, 1, 1), new float[] |
|
{ |
|
1/0.229f, 1/0.224f, 1/0.225f |
|
}); |
|
using var P = new TensorFloat(new TensorShape(1, 3, 1, 1), new float[] |
|
{ |
|
0.485f, 0.456f, 0.406f |
|
}); |
|
using var image2 = ops.Sub(image, P); |
|
return ops.Mul(image2, M); |
|
} |
|
|
|
private void OnDestroy() |
|
{ |
|
engine?.Dispose(); |
|
ops?.Dispose(); |
|
allocator?.Dispose(); |
|
} |
|
} |
|
|