using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using System;
using System.Collections.Generic;
using System.Linq;
class ImageClassifier
{
private InferenceSession _session;
public ImageClassifier(string modelPath)
{
var options = new SessionOptions();
options.GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL;
_session = new InferenceSession(modelPath, options);
// Print model info
Console.WriteLine("Model Inputs:");
foreach (var input in _session.InputMetadata)
{
Console.WriteLine($" {input.Key}: {input.Value.ElementDataType} {string.Join("x", input.Value.Dimensions)}");
}
}
public float[] Classify(float[] imageData, int[] shape)
{
// Create input tensor
var tensor = new DenseTensor<float>(imageData, shape);
var inputs = new List<NamedOnnxValue>
{
NamedOnnxValue.CreateFromTensor(_session.InputNames[0], tensor)
};
// Run inference
using (var results = _session.Run(inputs))
{
var output = results.First().AsTensor<float>();
return output.ToArray();
}
}
public void Dispose()
{
_session?.Dispose();
}
}
// Usage
class Program
{
static void Main()
{
using (var classifier = new ImageClassifier("resnet50.onnx"))
{
var imageData = new float[1 * 3 * 224 * 224];
// ... load and preprocess image data ...
var predictions = classifier.Classify(
imageData,
new[] { 1, 3, 224, 224 }
);
// Get top prediction
var maxIndex = Array.IndexOf(predictions, predictions.Max());
Console.WriteLine($"Predicted class: {maxIndex}");
Console.WriteLine($"Confidence: {predictions[maxIndex]:P2}");
}
}
}