我正在尝试进行对象检测。我正在使用Xamarin Forms和Xamarin.Tensorflow.Lite。首先,我加载我的模型:
AssetFileDescriptor fileDescriptor = assets.OpenFd("model.tflite");
FileInputStream inputStream = new FileInputStream(fileDescriptor.FileDescriptor);
FileChannel fileChannel = inputStream.Channel;
long startOffset = fileDescriptor.StartOffset;
long declaredLength = fileDescriptor.DeclaredLength;
var asd = fileChannel.Map(FileChannel.MapMode.ReadOnly, startOffset, declaredLength);
var model = new Xamarin.TensorFlow.Lite.Interpreter(asd);
我知道我应该调用model.Run(),但是我不太清楚该给它什么参数。我想给它一个图像并读回数据吗?怎么做?
首先,我们应该将图像读取到bitmap
var bitmap = await BitmapFactory.DecodeStreamAsync(image.GetStreamWithImageRotatedForExternalStorage());
然后像下面的代码一样将bitmap
转换为float[]
。>>
static float[] GetBitmapPixels(Bitmap bitmap) { var floatValues = new float[_inputSize * _inputSize * 3]; using (var scaledBitmap = Bitmap.CreateScaledBitmap(bitmap, _inputSize, _inputSize, false)) { using (var resizedBitmap = scaledBitmap.Copy(Bitmap.Config.Argb8888, false)) { var intValues = new int[_inputSize * _inputSize]; resizedBitmap.GetPixels(intValues, 0, resizedBitmap.Width, 0, 0, resizedBitmap.Width, resizedBitmap.Height); for (int i = 0; i < intValues.Length; ++i) { var val = intValues[i]; floatValues[i * 3 + 0] = ((val & 0xFF) - 104); floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - 117); floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - 123); } resizedBitmap.Recycle(); } scaledBitmap.Recycle(); } return floatValues; }
最后,我们可以读回数据。
public string RecognizeImage(Bitmap bitmap) { var outputNames = new[] { OutputName }; var floatValues = GetBitmapPixels(bitmap); var outputs = new float[labels.Count]; inferenceInterface.Feed(InputName, floatValues, 1, _inputSize, _inputSize, 3); inferenceInterface.Run(outputNames); inferenceInterface.Fetch(OutputName, outputs); var results = new List<Tuple<float, string>>(); for (var i = 0; i < outputs.Length; ++i) results.Add(Tuple.Create(outputs[i], labels[i])); return results.OrderByDescending(t => t.Item1).First().Item2; }
这里是有关它的博客。https://devblogs.microsoft.com/xamarin/android-apps-tensorflow/
这是演示。https://github.com/jimbobbennett/blog-samples/tree/master/UsingTensorFlowAndAzureInAndroid