YoloWrapper.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace Darknet
  4. {
  5. public class YoloWrapper : IDisposable
  6. {
  7. private const string YoloLibraryName = "yolo_cpp_dll.dll";
  8. private const int MaxObjects = 1000;
  9. [DllImport(YoloLibraryName, EntryPoint = "init")]
  10. private static extern int InitializeYolo(string configurationFilename, string weightsFilename, int gpu);
  11. [DllImport(YoloLibraryName, EntryPoint = "detect_image")]
  12. private static extern int DetectImage(string filename, ref BboxContainer container);
  13. [DllImport(YoloLibraryName, EntryPoint = "detect_mat")]
  14. private static extern int DetectImage(IntPtr pArray, int nSize, ref BboxContainer container);
  15. [DllImport(YoloLibraryName, EntryPoint = "dispose")]
  16. private static extern int DisposeYolo();
  17. [StructLayout(LayoutKind.Sequential)]
  18. public struct bbox_t
  19. {
  20. public UInt32 x, y, w, h; // (x,y) - top-left corner, (w, h) - width & height of bounded box
  21. public float prob; // confidence - probability that the object was found correctly
  22. public UInt32 obj_id; // class of object - from range [0, classes-1]
  23. public UInt32 track_id; // tracking id for video (0 - untracked, 1 - inf - tracked object)
  24. public UInt32 frames_counter;
  25. public float x_3d, y_3d, z_3d; // 3-D coordinates, if there is used 3D-stereo camera
  26. };
  27. [StructLayout(LayoutKind.Sequential)]
  28. public struct BboxContainer
  29. {
  30. [MarshalAs(UnmanagedType.ByValArray, SizeConst = MaxObjects)]
  31. public bbox_t[] candidates;
  32. }
  33. public YoloWrapper(string configurationFilename, string weightsFilename, int gpu)
  34. {
  35. InitializeYolo(configurationFilename, weightsFilename, gpu);
  36. }
  37. public void Dispose()
  38. {
  39. DisposeYolo();
  40. }
  41. public bbox_t[] Detect(string filename)
  42. {
  43. var container = new BboxContainer();
  44. var count = DetectImage(filename, ref container);
  45. return container.candidates;
  46. }
  47. public bbox_t[] Detect(byte[] imageData)
  48. {
  49. var container = new BboxContainer();
  50. var size = Marshal.SizeOf(imageData[0]) * imageData.Length;
  51. var pnt = Marshal.AllocHGlobal(size);
  52. try
  53. {
  54. // Copy the array to unmanaged memory.
  55. Marshal.Copy(imageData, 0, pnt, imageData.Length);
  56. var count = DetectImage(pnt, imageData.Length, ref container);
  57. if (count == -1)
  58. {
  59. throw new NotSupportedException($"{YoloLibraryName} has no OpenCV support");
  60. }
  61. }
  62. catch (Exception exception)
  63. {
  64. return null;
  65. }
  66. finally
  67. {
  68. // Free the unmanaged memory.
  69. Marshal.FreeHGlobal(pnt);
  70. }
  71. return container.candidates;
  72. }
  73. }
  74. }