using System; using System.Collections.Generic; namespace MMDeploy { #pragma warning disable 0649 internal unsafe struct CSegment { public int Height; public int Width; public int Classes; public int* Mask; } #pragma warning restore 0649 /// /// Output of Segmentor. /// public struct SegmentorOutput { /// /// Height of image. /// public int Height; /// /// Width if image. /// public int Width; /// /// Number of classes. /// public int Classes; /// /// Mask data. /// public int[] Mask; /// /// Initializes a new instance of the struct. /// /// height. /// width. /// classes. /// mask. public SegmentorOutput(int height, int width, int classes, int[] mask) { Height = height; Width = width; Classes = classes; Mask = new int[Height * Width]; Array.Copy(mask, this.Mask, mask.Length); } internal unsafe SegmentorOutput(CSegment* result) { Height = result->Height; Width = result->Width; Classes = result->Classes; Mask = new int[Height * Width]; int nbytes = Height * Width * sizeof(int); fixed (int* data = this.Mask) { Buffer.MemoryCopy(result->Mask, data, nbytes, nbytes); } } } /// /// Segmentor. /// public class Segmentor : DisposableObject { /// /// Initializes a new instance of the class. /// /// model path. /// device name. /// device id. public Segmentor(string modelPath, string deviceName, int deviceId) { ThrowException(NativeMethods.mmdeploy_segmentor_create_by_path(modelPath, deviceName, deviceId, out _handle)); } /// /// Get information of each image in a batch. /// /// input mats. /// Results of each input mat. public List Apply(Mat[] mats) { List output = new List(); unsafe { CSegment* results = null; fixed (Mat* _mats = mats) { ThrowException(NativeMethods.mmdeploy_segmentor_apply(_handle, _mats, mats.Length, &results)); } FormatResult(mats.Length, results, ref output, out var total); ReleaseResult(results, total); } return output; } private unsafe void FormatResult(int matCount, CSegment* results, ref List output, out int total) { total = 0; for (int i = 0; i < matCount; i++) { SegmentorOutput outi = new SegmentorOutput(results); results++; total++; output.Add(outi); } } private unsafe void ReleaseResult(CSegment* results, int count) { NativeMethods.mmdeploy_segmentor_release_result(results, count); } /// protected override void ReleaseHandle() { NativeMethods.mmdeploy_segmentor_destroy(_handle); } } }