MainWindow.xaml.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Reflection;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using System.Windows;
  10. using System.Windows.Media;
  11. using System.Windows.Media.Imaging;
  12. using System.Windows.Media.TextFormatting;
  13. using Path = System.IO.Path;
  14. namespace Test
  15. {
  16. [StructLayout(LayoutKind.Sequential)]
  17. internal struct Box
  18. {
  19. public float X;
  20. public float Y;
  21. public float Width;
  22. public float Height;
  23. public int Label;
  24. public float Prob;
  25. }
  26. [StructLayout(LayoutKind.Sequential)]
  27. public struct StructStringInfo
  28. {
  29. public IntPtr result;
  30. public int bufferSize;
  31. }
  32. /// <summary>
  33. /// Interaction logic for MainWindow.xaml
  34. /// </summary>
  35. public partial class MainWindow : Window
  36. {
  37. [DllImport("libYoloNcnn.dll")]
  38. private static extern void CreateNet(out IntPtr hDect, out IntPtr hRec, IntPtr dectBinName, IntPtr dectParaName, IntPtr recBinName, IntPtr recParaName, IntPtr keyTxtName);
  39. [DllImport("libYoloNcnn.dll")]
  40. private static extern unsafe void Test(IntPtr net, IntPtr net2, IntPtr input, int iw, int ih, ref StructStringInfo* ob, ref int count);
  41. [DllImport("libYoloNcnn.dll")]
  42. private static extern void FreeNet(IntPtr dectNet, IntPtr recNet);
  43. private IntPtr _detect;
  44. private IntPtr _rec;
  45. private byte[] _dectBinMem;
  46. private byte[] _dectParamMem;
  47. private byte[] _recBinMem;
  48. private byte[] _recParamMem;
  49. private readonly BitmapImage _image;
  50. private static readonly string[] ClassNames = {
  51. "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light",
  52. "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow",
  53. "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
  54. "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard",
  55. "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple",
  56. "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch",
  57. "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone",
  58. "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear",
  59. "hair drier", "toothbrush"
  60. };
  61. public MainWindow()
  62. {
  63. InitializeComponent();
  64. var imageFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test4.png");
  65. _image = new BitmapImage();
  66. _image.BeginInit();
  67. _image.StreamSource = new MemoryStream(File.ReadAllBytes(imageFile));
  68. _image.EndInit();
  69. TestImage.Source = _image;
  70. }
  71. private void DrawText(string textLine, Point loc, DrawingContext context)
  72. {
  73. var text = new FormattedText(textLine,
  74. CultureInfo.CurrentCulture,
  75. FlowDirection.LeftToRight,
  76. new Typeface(FontFamily, FontStyles.Normal, FontWeights.Normal, new FontStretch()),
  77. 36,
  78. Brushes.Black,
  79. null,
  80. 96);
  81. var textLocation = new Point(loc.X, loc.Y - text.Height);
  82. textLocation.Offset(1,0);
  83. context.DrawText(text, textLocation);
  84. }
  85. private unsafe void OnTestClick(object sender, RoutedEventArgs e)
  86. {
  87. var imageData = new byte[_image.PixelWidth * _image.PixelHeight * 4];
  88. _image.CopyPixels(imageData, _image.PixelWidth * 4, 0);
  89. var imgPtr = Marshal.UnsafeAddrOfPinnedArrayElement(imageData, 0);
  90. StructStringInfo* ob = null;
  91. int count = 0;
  92. Test(_detect, _rec, imgPtr, _image.PixelWidth, _image.PixelHeight, ref ob, ref count);
  93. // 访问每个字符串结果
  94. string[] resultString = new string[count];
  95. for (int i = 0; i < count; i++)
  96. {
  97. resultString[i] = Marshal.PtrToStringUTF8(ob[i].result/*, ob[i].bufferSize*/);
  98. }
  99. var rect = new Rect(new Size(_image.PixelWidth, _image.PixelHeight));
  100. var drawingVisual = new DrawingVisual();
  101. var drawingContext = drawingVisual.RenderOpen();
  102. //drawingContext.DrawImage(_image,rect);
  103. for (var i = 0; i < count; i++)
  104. {
  105. DrawText(resultString[i], new Point(100, 100 + 50 * i), drawingContext);
  106. }
  107. drawingContext.Close();
  108. var bmp = new RenderTargetBitmap(_image.PixelWidth, _image.PixelHeight, 96, 96, PixelFormats.Pbgra32);
  109. bmp.Render(drawingVisual);
  110. OutImage.Source = bmp;
  111. }
  112. private void OnLoadClick(object sender, RoutedEventArgs e)
  113. {
  114. var typeInfo = GetType().GetTypeInfo();
  115. var assemblyName = typeInfo.Assembly.GetName().Name;
  116. var dectbin = $"{assemblyName}.ValidModels.ch_PP-OCRv4_det_infer.bin";
  117. var stream = typeInfo.Assembly.GetManifestResourceStream(dectbin);
  118. if (stream == null)
  119. {
  120. throw new InvalidOperationException($"Resource not found: {dectbin}");
  121. }
  122. using (var ms = new MemoryStream())
  123. {
  124. stream.CopyTo(ms);
  125. _dectBinMem = ms.ToArray();
  126. }
  127. var dectparam = $"{assemblyName}.ValidModels.ch_PP-OCRv4_det_infer.param";
  128. stream = typeInfo.Assembly.GetManifestResourceStream(dectparam);
  129. if (stream == null)
  130. {
  131. throw new InvalidOperationException($"Resource not found: {dectparam}");
  132. }
  133. using (var ms = new MemoryStream())
  134. {
  135. stream.CopyTo(ms);
  136. _dectParamMem = ms.ToArray();
  137. }
  138. var recbin = $"{assemblyName}.ValidModels.ch_PP-OCRv3_rec.bin";
  139. stream = typeInfo.Assembly.GetManifestResourceStream(recbin);
  140. if (stream == null)
  141. {
  142. throw new InvalidOperationException($"Resource not found: {recbin}");
  143. }
  144. using (var ms = new MemoryStream())
  145. {
  146. stream.CopyTo(ms);
  147. _recBinMem = ms.ToArray();
  148. }
  149. var recparam = $"{assemblyName}.ValidModels.ch_PP-OCRv3_rec.param";
  150. stream = typeInfo.Assembly.GetManifestResourceStream(recparam);
  151. if (stream == null)
  152. {
  153. throw new InvalidOperationException($"Resource not found: {recparam}");
  154. }
  155. using (var ms = new MemoryStream())
  156. {
  157. stream.CopyTo(ms);
  158. _recParamMem = ms.ToArray();
  159. }
  160. var dectbinPtr = Marshal.UnsafeAddrOfPinnedArrayElement(_dectBinMem, 0);
  161. var dectparamPtr = Marshal.UnsafeAddrOfPinnedArrayElement(_dectParamMem, 0);
  162. var recbinPtr = Marshal.UnsafeAddrOfPinnedArrayElement(_recBinMem, 0);
  163. var recparamPtr = Marshal.UnsafeAddrOfPinnedArrayElement(_recParamMem, 0);
  164. IntPtr keyName = Marshal.StringToHGlobalAnsi("ppocr_keys_v1.txt");
  165. CreateNet(out _detect, out _rec, dectbinPtr, dectparamPtr, recbinPtr, recparamPtr, keyName);
  166. if (_detect != IntPtr.Zero)
  167. {
  168. LoadButton.IsEnabled = false;
  169. TestButton.IsEnabled = true;
  170. BenchmarkButton.IsEnabled = true;
  171. }
  172. }
  173. protected override void OnClosing(CancelEventArgs e)
  174. {
  175. if (_detect != IntPtr.Zero)
  176. {
  177. FreeNet(_detect, _rec);
  178. }
  179. base.OnClosing(e);
  180. }
  181. private unsafe void OnBenchmarkClick(object sender, RoutedEventArgs e)
  182. {
  183. var imageData = new byte[_image.PixelWidth * _image.PixelHeight * 4];
  184. _image.CopyPixels(imageData, _image.PixelWidth * 4, 0);
  185. var imgPtr = Marshal.UnsafeAddrOfPinnedArrayElement(imageData, 0);
  186. var boxes = new Box[100];
  187. var boxPtr = Marshal.UnsafeAddrOfPinnedArrayElement(boxes, 0);
  188. var start = Environment.TickCount;
  189. for (var i = 0; i < 100; i++)
  190. {
  191. StructStringInfo* ob = null;
  192. int count = 0;
  193. Test(_detect, _rec, imgPtr, _image.PixelWidth, _image.PixelHeight, ref ob, ref count);
  194. // 访问每个字符串结果
  195. string[] resultString = new string[count];
  196. for (int j = 0; j < count; j++)
  197. {
  198. resultString[i] = Marshal.PtrToStringUTF8(ob[i].result/*, ob[i].bufferSize*/);
  199. }
  200. }
  201. var total = Environment.TickCount - start;
  202. var seconds = total / 1000d;
  203. var fps = (int)(100 / seconds);
  204. MessageBox.Show($"FPS: {fps}");
  205. }
  206. }
  207. }