using System.Collections.Generic;
namespace MMDeploy
{
///
/// Single classification result of a picture.
/// A picture may contains multiple reuslts.
///
public struct Label
{
///
/// Id.
///
public int Id;
///
/// Score.
///
public float Score;
///
/// Initializes a new instance of the struct.
///
/// id.
/// score.
public Label(int id, float score)
{
Id = id;
Score = score;
}
}
///
/// Output of Classifier.
///
public struct ClassifierOutput
{
///
/// Classification results for single image.
///
public List Results;
///
/// Add result to single image.
///
/// id.
/// score.
public void Add(int id, float score)
{
if (Results == null)
{
Results = new List();
}
Results.Add(new Label(id, score));
}
///
/// Gets number of output.
///
public int Count
{
get { return (Results == null) ? 0 : Results.Count; }
}
}
///
/// classifier.
///
public class Classifier : DisposableObject
{
///
/// Initializes a new instance of the class.
///
/// model path.
/// device name.
/// deviceId.
public Classifier(string modelPath, string deviceName, int deviceId)
{
ThrowException(NativeMethods.mmdeploy_classifier_create_by_path(modelPath, deviceName, deviceId, out _handle));
}
///
/// Get label information of each image in a batch.
///
/// input mats.
/// Results of each input mat.
public List Apply(Mat[] mats)
{
List output = new List();
unsafe
{
Label* results = null;
int* resultCount = null;
fixed (Mat* _mats = mats)
{
ThrowException(NativeMethods.mmdeploy_classifier_apply(_handle, _mats, mats.Length, &results, &resultCount));
}
FormatResult(mats.Length, resultCount, results, ref output, out var total);
ReleaseResult(results, resultCount, total);
}
return output;
}
private unsafe void FormatResult(int matCount, int* resultCount, Label* results, ref List output, out int total)
{
total = 0;
for (int i = 0; i < matCount; i++)
{
ClassifierOutput outi = default;
for (int j = 0; j < resultCount[i]; j++)
{
outi.Add(results->Id, results->Score);
results++;
total++;
}
output.Add(outi);
}
}
private unsafe void ReleaseResult(Label* results, int* resultCount, int count)
{
NativeMethods.mmdeploy_classifier_release_result(results, resultCount, count);
}
///
protected override void ReleaseHandle()
{
NativeMethods.mmdeploy_classifier_destroy(_handle);
}
}
}