Form1.cs 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075
  1. using System;
  2. using System.IO;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Drawing;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Windows.Forms;
  12. using System.Runtime.InteropServices;
  13. using System.Drawing.Imaging;
  14. using OpenCvSharp;
  15. namespace WinFormsApp_final
  16. {
  17. public partial class Form1 : Form
  18. {
  19. /**********************************************************************/
  20. /***************** 1.Reasoning DLL import implementation ****************/
  21. /**********************************************************************/
  22. // Load inference correlation methods
  23. [DllImport("model_infer.dll", EntryPoint = "InitModel")] // Model unified initialization method: need yml、pdmodel、pdiparams
  24. public static extern void InitModel(string model_type, string model_filename, string params_filename, string cfg_file, bool use_gpu, int gpu_id, ref byte paddlex_model_type);
  25. [DllImport("model_infer.dll", EntryPoint = "Det_ModelPredict")] // PaddleDetection Model reasoning method
  26. public static extern void Det_ModelPredict(byte[] img, int W, int H, int C, IntPtr output, int[] BoxesNum, ref byte label);
  27. [DllImport("model_infer.dll", EntryPoint = "Seg_ModelPredict")] // PaddleSeg Model reasoning method
  28. public static extern void Seg_ModelPredict(byte[] img, int W, int H, int C, ref byte output);
  29. [DllImport("model_infer.dll", EntryPoint = "Cls_ModelPredict")] // PaddleClas Model reasoning method
  30. public static extern void Cls_ModelPredict(byte[] img, int W, int H, int C, ref float score, ref byte category, ref int category_id);
  31. [DllImport("model_infer.dll", EntryPoint = "Mask_ModelPredict")] // Paddlex-MaskRCNN Model reasoning method
  32. public static extern void Mask_ModelPredict(byte[] img, int W, int H, int C, IntPtr output, ref byte Mask_output, int[] BoxesNum, ref byte label);
  33. [DllImport("model_infer.dll", EntryPoint = "DestructModel")] // Segmentation, detection, identification model destruction method
  34. public static extern void DestructModel();
  35. /**********************************************************************/
  36. /****************** 2.Statement of control parameters *****************/
  37. /**********************************************************************/
  38. string imgfile = null; // Single image path
  39. List<string> imgfiles = new List<string>(); // Multiple image paths
  40. string videofile = null; // Reasoning the video path
  41. bool use_gpu = false; // Whether to use GPU
  42. int gpu_id = 0;
  43. float det_threshold = 0.5F;
  44. string model_type = "det";
  45. string model_filename = null; // *.pdmodel
  46. string params_filename = null; // *.pdiparams
  47. string cfg_file = null; // *.yml
  48. byte[] paddlex_model_type = new byte[10]; // det/seg/clas + \0
  49. bool paddlex_doing = false;
  50. string[] img_type = {"jpg", "png", "JPEG", "jpeg"};
  51. static int has_model_init = 0;
  52. static int is_infer = 0;
  53. static int isBreakInfer = 0;
  54. static int infer_one_img_flag = 0;
  55. static int infer_many_img_flag = 0;
  56. static int infer_video_img_flag = 0;
  57. int continue_infer_delay = 50;
  58. /**********************************************************************/
  59. /************** 3.Form loading and closing implementation ***************/
  60. /**********************************************************************/
  61. public Form1()
  62. {
  63. InitializeComponent();
  64. }
  65. private void Form1_Load(object sender, EventArgs e)
  66. {
  67. comboBox1.SelectedIndex = 0;
  68. comboBox2.SelectedIndex = 0;
  69. comboBox3.SelectedIndex = 5;
  70. numericUpDown1.Value = 50;
  71. label7.Text = "0.00";
  72. textBox1.Text = "0";
  73. }
  74. private void Form1_FromClosing(object sender, EventArgs e)
  75. {
  76. while (is_infer != 0)
  77. {
  78. isBreakInfer = 1;
  79. }
  80. if (has_model_init == 1)
  81. {
  82. DestructModel();
  83. }
  84. }
  85. /**********************************************************************/
  86. /***************** 4.Detail parameter option implementation ***************/
  87. /**********************************************************************/
  88. int comboBox_clicked = 0;
  89. int comboBox1_last_index = 0;
  90. // Select run environment - GPU or CPU
  91. private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
  92. {
  93. if (is_infer == 1 && comboBox_clicked == 0)
  94. {
  95. MessageBox.Show("正在推理中,请推理完成后再选择运行环境重新初始化!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
  96. comboBox_clicked = 1;
  97. comboBox1.SelectedIndex = comboBox1_last_index;
  98. return;
  99. }
  100. if (has_model_init == 1 && comboBox_clicked == 0)
  101. {
  102. MessageBox.Show("模型已初始化,请销毁模型后再进行运行环境选择!\n(CPU,GPU)", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
  103. comboBox_clicked = 1;
  104. comboBox1.SelectedIndex = comboBox1_last_index;
  105. return;
  106. }
  107. if (comboBox1.SelectedItem.ToString() == "GPU")
  108. {
  109. use_gpu = true;
  110. }
  111. else if (comboBox1.SelectedItem.ToString() == "CPU")
  112. {
  113. use_gpu = false;
  114. }
  115. comboBox1_last_index = comboBox1.SelectedIndex;
  116. comboBox_clicked = 0;
  117. }
  118. int last_gpu_id = 0;
  119. int gpu_id_done = 0;
  120. private void textBox1_TextChanged(object sender, EventArgs e)
  121. {
  122. if (is_infer == 1 && gpu_id_done == 0)
  123. {
  124. MessageBox.Show("正在推理中,请推理完成后再选择指定GPU重新初始化!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
  125. gpu_id_done = 1;
  126. gpu_id = last_gpu_id;
  127. textBox1.Text = $"{gpu_id}";
  128. return;
  129. }
  130. if (has_model_init == 1 && gpu_id_done == 0)
  131. {
  132. MessageBox.Show("模型已初始化,请销毁模型后再进行GPU指定!\n(GPU:x)", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
  133. gpu_id_done = 1;
  134. gpu_id = last_gpu_id;
  135. textBox1.Text = $"{gpu_id}";
  136. return;
  137. }
  138. if (gpu_id_done == 0)
  139. {
  140. string gpu_id_str = textBox1.Text.ToString();
  141. if (gpu_id_str.Length != 0)
  142. {
  143. last_gpu_id = gpu_id;
  144. try
  145. {
  146. gpu_id = Int32.Parse(gpu_id_str);
  147. }
  148. catch (Exception ex)
  149. {
  150. gpu_id = last_gpu_id;
  151. textBox1.Text = $"{gpu_id}";
  152. MessageBox.Show("GPU_ID只能输入数字!");
  153. }
  154. }
  155. }
  156. gpu_id_done = 0;
  157. }
  158. int comboBox2_last_index = 0;
  159. // Choice of type of model to perform reasoning
  160. private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
  161. {
  162. if (is_infer == 1 && comboBox_clicked == 0)
  163. {
  164. MessageBox.Show("正在推理中,请推理完成后再选择模型类型重新初始化!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
  165. comboBox_clicked = 1;
  166. comboBox2.SelectedIndex = comboBox2_last_index;
  167. return;
  168. }
  169. if (has_model_init == 1 && comboBox_clicked == 0)
  170. {
  171. MessageBox.Show("模型已初始化,请销毁模型后再进行模型类型选择!\n(det,seg,clas)", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
  172. comboBox_clicked = 1;
  173. comboBox2.SelectedIndex = comboBox2_last_index;
  174. return;
  175. }
  176. // There are three types
  177. if (comboBox2.SelectedItem.ToString() == "det") // Load detection model
  178. {
  179. model_type = comboBox2.SelectedItem.ToString();
  180. paddlex_doing = false; // Enter non-PADDLEX mode -- detection
  181. }
  182. else if (comboBox2.SelectedItem.ToString() == "seg") // Load segmentation model
  183. {
  184. model_type = comboBox2.SelectedItem.ToString();
  185. paddlex_doing = false;
  186. }
  187. else if (comboBox2.SelectedItem.ToString() == "clas") // Load recognition model
  188. {
  189. model_type = comboBox2.SelectedItem.ToString();
  190. paddlex_doing = false;
  191. }
  192. else if (comboBox2.SelectedItem.ToString() == "mask") // Loading instance split Maskrcnn model
  193. {
  194. model_type = comboBox2.SelectedItem.ToString();
  195. paddlex_doing = false;
  196. }
  197. else if (comboBox2.SelectedItem.ToString() == "paddlex") // Load paddlex model
  198. {
  199. model_type = comboBox2.SelectedItem.ToString();
  200. // Repeat Paddlex, do not modify the status
  201. }
  202. comboBox2_last_index = comboBox2.SelectedIndex;
  203. comboBox_clicked = 0;
  204. }
  205. int comboBox3_last_index = 0;
  206. // Set the detection threshold for target detection
  207. private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
  208. {
  209. if (is_infer == 1 && comboBox_clicked == 0)
  210. {
  211. MessageBox.Show("正在推理中,检测阈值修改将在本次模型推理完成后生效!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
  212. comboBox_clicked = 1;
  213. comboBox3.SelectedIndex = comboBox3_last_index;
  214. return;
  215. }
  216. det_threshold = float.Parse(comboBox3.SelectedItem.ToString());
  217. comboBox3_last_index = comboBox3.SelectedIndex;
  218. comboBox_clicked = 0;
  219. }
  220. // Continuous reasoning interval length - picture folder reasoning
  221. private void numericUpDown1_ValueChanged(object sender, EventArgs e)
  222. {
  223. continue_infer_delay = ((int)numericUpDown1.Value);
  224. }
  225. /**********************************************************************/
  226. /***************** 5.Select control components implementation ***************/
  227. /**********************************************************************/
  228. // Load the model related file folder
  229. private void button1_Click(object sender, EventArgs e)
  230. {
  231. if (is_infer == 1)
  232. {
  233. MessageBox.Show("正在推理中,请推理完成后再初始化加载模型!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  234. return;
  235. }
  236. if (!CheckMaskRCNN_workOnGpu(model_type, use_gpu)) // The Maskrcnn environment is not in the GPU, then an error reminder
  237. {
  238. MessageBox.Show("MaskRCNN推理仅支持GPU环境,请重新选择启动环境!\n(因为CPU环境可能存在内存不足,导致推理失败。)", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  239. return;
  240. }
  241. int dir_load_flag = 0;
  242. string dir_path = null;
  243. folderBrowserDialog1.Description = "请选择模型文件夹";
  244. DialogResult folder = folderBrowserDialog1.ShowDialog();
  245. if (folder == DialogResult.OK || folder == DialogResult.Yes)
  246. {
  247. dir_path = folderBrowserDialog1.SelectedPath;
  248. if (string.IsNullOrEmpty(dir_path))
  249. {
  250. MessageBox.Show("请选择模型路径/模型路径为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  251. dir_load_flag = 0;
  252. }
  253. else
  254. {
  255. dir_load_flag = 1;
  256. }
  257. }
  258. if (dir_load_flag == 1)
  259. {
  260. List<FileInfo> model_lst = new List<FileInfo>();
  261. List<FileInfo> params_lst = new List<FileInfo>();
  262. List<FileInfo> cfg_lst = new List<FileInfo>();
  263. model_lst = getFile(dir_path, ".pdmodel", model_lst);
  264. params_lst = getFile(dir_path, ".pdiparams", params_lst);
  265. cfg_lst = getFile(dir_path, ".yml", cfg_lst);
  266. if (cfg_lst.Count == 0)
  267. cfg_lst = getFile(dir_path, ".yaml", cfg_lst);
  268. if (model_lst.Count != 1 || params_lst.Count != 1)
  269. {
  270. MessageBox.Show("模型文件加载失败!\n请注意模型文件夹下应包含以下文件各一个:\n*.pdmodel, *.pdiparams", "提示");
  271. return;
  272. }
  273. model_filename = model_lst[0].FullName;
  274. params_filename = params_lst[0].FullName;
  275. if (cfg_lst.Count == 0)
  276. {
  277. MessageBox.Show("模型文件加载失败!\n请注意模型文件夹下应包含以下文件:\nmodel.yml/model.yaml", "提示");
  278. return;
  279. }
  280. else if (cfg_lst.Count > 2) // Excessive YML, > 2
  281. {
  282. MessageBox.Show("模型文件加载失败!\n请注意模型文件夹下应至多包含以下文件(yml文件个数不得超过2):\nmodel.yml/model.yaml,pipeline.yml/pipeline.yaml", "提示");
  283. return;
  284. }
  285. else if (cfg_lst.Count == 2) // Processing for the case of multiple YML files
  286. {
  287. for (int i = 0; i < 2; i++)
  288. {
  289. if (cfg_lst[i].Name == "model.yml" || cfg_lst[i].Name == "model.yaml")
  290. {
  291. cfg_file = cfg_lst[i].FullName;
  292. break;
  293. }
  294. }
  295. }
  296. else if (cfg_lst.Count == 1)
  297. {
  298. cfg_file = cfg_lst[0].FullName;
  299. }
  300. int raise_ex_flag = 0;
  301. int is_Mask = 0;
  302. if (has_model_init == 1)
  303. {
  304. DestructModel();
  305. try
  306. {
  307. if (paddlex_doing == true) model_type = "paddlex";
  308. if (model_type == "mask")
  309. {
  310. model_type = "paddlex";
  311. is_Mask = 1;
  312. }
  313. InitModel(model_type, model_filename, params_filename, cfg_file, use_gpu, gpu_id, ref paddlex_model_type[0]);
  314. if (is_Mask == 1)
  315. {
  316. model_type = "mask";
  317. is_Mask = 0;
  318. }
  319. if (model_type == "paddlex")
  320. {
  321. paddlex_doing = true;
  322. model_type = System.Text.Encoding.UTF8.GetString(paddlex_model_type).Split('\0')[0];
  323. }
  324. }
  325. catch (Exception ex)
  326. {
  327. raise_ex_flag = 1;
  328. MessageBox.Show("1.请确定文件中包含有效的模型文件(*.pdmodel, *.pdiparams, *.yml)!\n2.请检查模型文件与模型类型是否一致!\n3.其它原因:GPU号有误,yml中预处理有误...", "模型初始化失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  329. }
  330. }
  331. else
  332. {
  333. try
  334. {
  335. if (paddlex_doing == true) model_type = "paddlex";
  336. if (model_type == "mask")
  337. {
  338. model_type = "paddlex";
  339. is_Mask = 1;
  340. }
  341. InitModel(model_type, model_filename, params_filename, cfg_file, use_gpu, gpu_id, ref paddlex_model_type[0]);
  342. if (is_Mask == 1)
  343. {
  344. model_type = "mask";
  345. is_Mask = 0;
  346. }
  347. if (model_type == "paddlex")
  348. {
  349. paddlex_doing = true;
  350. model_type = System.Text.Encoding.UTF8.GetString(paddlex_model_type).Split('\0')[0];
  351. }
  352. }
  353. catch (Exception ex)
  354. {
  355. raise_ex_flag = 1;
  356. MessageBox.Show("1.请确定文件中包含有效的模型文件(*.pdmodel, *.pdiparams, *.yml)!\n2.请检查模型文件与模型类型是否一致!\n3.其它原因:GPU号有误,yml中预处理有误...", "模型初始化失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  357. }
  358. }
  359. if (raise_ex_flag == 0)
  360. {
  361. has_model_init = 1;
  362. if (use_gpu)
  363. {
  364. if (is_Mask == 1)
  365. {
  366. model_type = "mask";
  367. is_Mask = 0;
  368. }
  369. MessageBox.Show($"模型文件已加载到GPU:{gpu_id}!\n(模型类型为: {model_type.Split('\0')[0]})", "提示");
  370. }
  371. else
  372. {
  373. MessageBox.Show($"模型类型为: {model_type.Split('\0')[0]}", "提示");
  374. }
  375. button1.Text = "模型已初始化";
  376. }
  377. }
  378. }
  379. // Load a single image
  380. private void button2_Click(object sender, EventArgs e)
  381. {
  382. if (is_infer == 1)
  383. {
  384. MessageBox.Show("正在推理中,请推理完成后再选择推理数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  385. return;
  386. }
  387. int has_load_img_file_flag = 1;
  388. openFileDialog1.Filter = "(*.png;*.jpg;*.JPEG;*.jpeg)|*.*";
  389. DialogResult dr = openFileDialog1.ShowDialog();
  390. string filename = openFileDialog1.FileName;
  391. if (dr != System.Windows.Forms.DialogResult.OK || string.IsNullOrEmpty(filename))
  392. {
  393. has_load_img_file_flag = 0;
  394. }
  395. if (has_load_img_file_flag==1)
  396. {
  397. string[] final_tag = filename.Split('.');
  398. int flag = 0;
  399. foreach (string type in img_type)
  400. {
  401. if (final_tag[1] == type)
  402. {
  403. flag = 1;
  404. imgfile = filename;
  405. pictureBox1.Image = Image.FromFile(imgfile);
  406. pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
  407. videofile = null;
  408. imgfiles.Clear();
  409. MessageBox.Show("图片加载完成!", "提示");
  410. button2.Text = "图片已加载";
  411. button3.Text = "加载图片文件夹";
  412. button4.Text = "加载视频流";
  413. }
  414. }
  415. }
  416. }
  417. // Load picture folder
  418. private void button3_Click(object sender, EventArgs e)
  419. {
  420. if (is_infer == 1)
  421. {
  422. MessageBox.Show("正在推理中,请推理完成后再选择推理数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  423. return;
  424. }
  425. int img_dir_load_flag = 0;
  426. string img_dir_path = null;
  427. folderBrowserDialog1.Description = "请选择模型文件夹";
  428. DialogResult folder = folderBrowserDialog1.ShowDialog();
  429. if (folder == DialogResult.OK || folder == DialogResult.Yes)
  430. {
  431. img_dir_path = folderBrowserDialog1.SelectedPath;
  432. if (string.IsNullOrEmpty(img_dir_path)) // 判断是否选择了模型文件
  433. {
  434. MessageBox.Show("请选择图片文件夹路径/图片文件夹路径为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  435. img_dir_load_flag = 0;
  436. }
  437. else
  438. {
  439. img_dir_load_flag = 1;
  440. }
  441. }
  442. if (img_dir_load_flag == 1)
  443. {
  444. List<FileInfo> lst = new List<FileInfo>();
  445. lst = getFile(img_dir_path, ".jpg", lst);
  446. lst = getFile(img_dir_path, ".png", lst);
  447. lst = getFile(img_dir_path, ".JPEG", lst);
  448. foreach (FileInfo Image_File in lst)
  449. {
  450. imgfiles.Add(Image_File.FullName);
  451. }
  452. if (imgfiles.Count == 0)
  453. {
  454. MessageBox.Show("请输入选择非空/包含正确图片类型的图片文件夹!\n(*.png, *.jpg, *.JPEG)", "图片解析失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  455. return;
  456. }
  457. pictureBox1.Image = Image.FromFile(imgfiles[0]);
  458. pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
  459. imgfile = null;
  460. videofile = null;
  461. MessageBox.Show("图片文件夹加载完成!", "提示");
  462. button3.Text = "图片文件夹已加载";
  463. button2.Text = "加载图片";
  464. button4.Text = "加载视频流";
  465. }
  466. }
  467. // Load the video stream
  468. private void button4_Click(object sender, EventArgs e)
  469. {
  470. if (is_infer == 1)
  471. {
  472. MessageBox.Show("正在推理中,请推理完成后再选择推理数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  473. return;
  474. }
  475. int has_load_mp4_file_flag = 1;
  476. openFileDialog1.Filter = "(*.mp4)|*.*";
  477. DialogResult dr = openFileDialog1.ShowDialog();
  478. string filename = openFileDialog1.FileName;
  479. if (dr != System.Windows.Forms.DialogResult.OK || string.IsNullOrEmpty(filename))
  480. {
  481. if (string.IsNullOrEmpty(filename)) MessageBox.Show("请选择视频(*.mp4)文件!", "视频路径为空", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  482. has_load_mp4_file_flag = 0;
  483. }
  484. if (has_load_mp4_file_flag==1)
  485. {
  486. string[] final_tag = filename.Split('.');
  487. if (final_tag[1] == "mp4")
  488. {
  489. videofile = filename;
  490. Bitmap image = null;
  491. Mat frame = new Mat();
  492. VideoCapture capture = new VideoCapture();
  493. capture.Open(videofile);
  494. bool read_success = capture.Read(frame);
  495. if (!read_success)
  496. {
  497. MessageBox.Show("无法读取视频的帧!!!", "提示");
  498. }
  499. else
  500. {
  501. image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(frame);
  502. pictureBox1.Image = image;
  503. pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
  504. capture = null;
  505. frame = null;
  506. image = null;
  507. imgfile = null;
  508. imgfiles.Clear();
  509. MessageBox.Show("视频加载完成!", "提示");
  510. button4.Text = "视频流已加载";
  511. button2.Text = "加载图片";
  512. button3.Text = "加载图片文件夹";
  513. }
  514. }
  515. else
  516. {
  517. MessageBox.Show("请选择mp4视频文件!", "视频资源加载失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  518. }
  519. }
  520. }
  521. // Perform reasoning
  522. private void button5_Click(object sender, EventArgs e)
  523. {
  524. if (imgfile != null && is_infer==0 && has_model_init == 1) // Single picture prediction
  525. {
  526. Thread infer_one_img_thread = null;
  527. if (model_type == "det") infer_one_img_thread = new Thread(new ThreadStart(delegate { det_infer_one_img(); }));
  528. else if (model_type == "seg") infer_one_img_thread = new Thread(new ThreadStart(delegate { seg_infer_one_img(); }));
  529. else if (model_type == "clas") infer_one_img_thread = new Thread(new ThreadStart(delegate { cls_infer_one_img(); }));
  530. else if (model_type == "mask") infer_one_img_thread = new Thread(new ThreadStart(delegate { mask_infer_one_img(); }));
  531. MessageBox.Show("开始图片推理任务!", "提示");
  532. infer_one_img_thread.Start();
  533. infer_one_img_flag = 1;
  534. }
  535. else if (imgfiles.Count != 0 && is_infer == 0 && has_model_init == 1) // Picture folder prediction
  536. {
  537. Thread infer_many_img_thread = null;
  538. if (model_type == "det") infer_many_img_thread = new Thread(new ThreadStart(delegate { det_infer_many_img(); }));
  539. else if (model_type == "seg") infer_many_img_thread = new Thread(new ThreadStart(delegate { seg_infer_many_img(); }));
  540. else if (model_type == "clas") infer_many_img_thread = new Thread(new ThreadStart(delegate { cls_infer_many_img(); }));
  541. else if (model_type == "mask") infer_many_img_thread = new Thread(new ThreadStart(delegate { mask_infer_many_img(); }));
  542. MessageBox.Show("开始图片文件夹推理任务!", "提示");
  543. infer_many_img_thread.Start();
  544. infer_many_img_flag = 1;
  545. }
  546. else if (videofile != null && is_infer == 0 && has_model_init == 1) // Video reasoning
  547. {
  548. Thread infer_video_img_thread = null;
  549. if (model_type == "det") infer_video_img_thread = new Thread(new ThreadStart(delegate { det_infer_video_img(); }));
  550. else if (model_type == "seg") infer_video_img_thread = new Thread(new ThreadStart(delegate { seg_infer_video_img(); }));
  551. else if (model_type == "clas") infer_video_img_thread = new Thread(new ThreadStart(delegate { cls_infer_video_img(); }));
  552. else if (model_type == "mask") infer_video_img_thread = new Thread(new ThreadStart(delegate { mask_infer_video_img(); }));
  553. MessageBox.Show("开始视频推理任务!", "提示");
  554. infer_video_img_thread.Start();
  555. infer_video_img_flag = 1;
  556. }
  557. else if (is_infer == 1 && has_model_init == 1)
  558. {
  559. if (infer_one_img_flag == 1) MessageBox.Show("正在进行推理任务!", "请勿再执行图片推理任务", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  560. if (infer_many_img_flag == 1) MessageBox.Show("正在进行推理任务!", "请勿再执行图片文件夹推理任务", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  561. if (infer_video_img_flag == 1) MessageBox.Show("正在进行推理任务!", "请勿再执行视频推理任务", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  562. }
  563. if (has_model_init == 0 && (imgfile == null && imgfiles.Count == 0 && videofile == null))
  564. {
  565. MessageBox.Show("请先初始化模型,并选择加载的推理数据后,再点击模型推理!", "推理执行失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  566. }
  567. else if (has_model_init == 0 && (imgfile != null || imgfiles.Count != 0 || videofile != null))
  568. {
  569. MessageBox.Show("请初始化模型,再点击模型推理!", "推理执行失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  570. }
  571. else if (has_model_init != 0 && (imgfile == null && imgfiles.Count == 0 && videofile == null))
  572. {
  573. MessageBox.Show("请选择加载的推理数据,再点击模型推理!", "推理执行失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  574. }
  575. }
  576. // Termination of the reasoning
  577. private void button6_Click(object sender, EventArgs e)
  578. {
  579. isBreakInfer = 1;
  580. }
  581. // Destroy the initialized model
  582. private void button7_Click(object sender, EventArgs e)
  583. {
  584. if (is_infer == 0)
  585. {
  586. if (has_model_init == 1)
  587. {
  588. try
  589. {
  590. DestructModel();
  591. }
  592. catch (Exception ex)
  593. {
  594. MessageBox.Show("当前未初始化模型,无需销毁!", "模型销毁失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  595. }
  596. has_model_init = 0;
  597. }
  598. button1.Text = "初始化模型";
  599. }
  600. else
  601. {
  602. MessageBox.Show("请先中断模型推理,再销毁已初始化的模型!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
  603. }
  604. }
  605. /***********************************************************************/
  606. /***************** 6.Visual reasoning implementation **************/
  607. /***********************************************************************/
  608. private void det_infer_one_img()
  609. {
  610. is_infer = 1;
  611. byte[] color_map = get_color_map_list(256);
  612. //Bitmap bmp = new Bitmap(imgfile);
  613. Bitmap bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(Cv2.ImRead(imgfile));
  614. byte[] inputData = GetBGRValues(bmp, out int stride);
  615. float[] resultlist = new float[600];
  616. IntPtr results = FloatToIntptr(resultlist);
  617. int[] boxesInfo = new int[1]; // 10 boundingbox
  618. byte[] labellist = new byte[1000];
  619. int raise_ex_flag = 0;
  620. try
  621. {
  622. TimeSpan infer_start_time = new TimeSpan(DateTime.Now.Ticks);
  623. // The fourth parameter is the number of channels for inputting images
  624. Det_ModelPredict(inputData, bmp.Width, bmp.Height, 3, results, boxesInfo, ref labellist[0]);
  625. TimeSpan infer_end_time = new TimeSpan(DateTime.Now.Ticks);
  626. string strGet = System.Text.Encoding.Default.GetString(labellist, 0, labellist.Length);
  627. string[] predict_Label_List = strGet.Split(' ');
  628. using OpenCvSharp.Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);
  629. for (int i = 0; i < boxesInfo[0]; i++)
  630. {
  631. int labelindex = Convert.ToInt32(resultlist[i * 6 + 0]);
  632. float score = resultlist[i * 6 + 1];
  633. float left = resultlist[i * 6 + 2];
  634. float top = resultlist[i * 6 + 3];
  635. float right = resultlist[i * 6 + 4];
  636. float down = resultlist[i * 6 + 5];
  637. if (score > det_threshold)
  638. {
  639. int[] color_ = { (int)(color_map[(labelindex%256)*3]),
  640. (int)(color_map[(labelindex % 256) * 3 + 1]),
  641. (int)(color_map[(labelindex % 256) * 3 + 2]) };
  642. var text_size = Cv2.GetTextSize($"{predict_Label_List[i]}-{labelindex}-{score:f2}",
  643. HersheyFonts.HersheySimplex, 1, 2, out int baseline);
  644. int left_down_x = (int)left + 22;
  645. int left_down_y = (int)top + text_size.Height;
  646. Cv2.Rectangle(mat, new OpenCvSharp.Rect((int)left, (int)top, (int)right, (int)down), new OpenCvSharp.Scalar(color_[0], color_[1], color_[2]), 2, LineTypes.AntiAlias);//LineTypes.AntiAlias:反锯齿效果
  647. Cv2.PutText(mat, $"{predict_Label_List[i]}-{labelindex}-: {score:f2}", new OpenCvSharp.Point(left_down_x, left_down_y), HersheyFonts.HersheySimplex, 1, new OpenCvSharp.Scalar(color_[0], color_[1], color_[2]), 2, LineTypes.Link4);
  648. }
  649. }
  650. bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
  651. if (pictureBox2.Image != null) pictureBox2.Image.Dispose();
  652. pictureBox2.Image = bmp;
  653. pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
  654. TimeSpan start2end_time = infer_end_time.Subtract(infer_start_time).Duration();
  655. double cost_milliseconds = start2end_time.TotalMilliseconds;
  656. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  657. label7.Invoke(AsyncUIDelegate, new object[] { $"{cost_milliseconds:f2}" });
  658. }
  659. catch (Exception e)
  660. {
  661. raise_ex_flag = 1;
  662. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  663. label7.Invoke(AsyncUIDelegate, new object[] { "0.00" });
  664. MessageBox.Show("1.请检查模型文件与模型类型是否一致!\n2.内存溢出,yml预处理有误,图片格式确保为1/3通道...", "模型运行失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  665. }
  666. isBreakInfer = 0;
  667. is_infer = 0;
  668. infer_one_img_flag = 0;
  669. if (raise_ex_flag == 0) MessageBox.Show("图片推理完成!");
  670. }
  671. private void det_infer_many_img()
  672. {
  673. is_infer = 1;
  674. byte[] color_map = get_color_map_list(256);
  675. int raise_ex_flag = 0;
  676. try
  677. {
  678. foreach (string img_file in imgfiles)
  679. {
  680. if (isBreakInfer == 1) break;
  681. Bitmap show_image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(Cv2.ImRead(img_file));
  682. Bitmap bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(Cv2.ImRead(img_file));
  683. byte[] inputData = GetBGRValues(bmp, out int stride);
  684. float[] resultlist = new float[600];
  685. IntPtr results = FloatToIntptr(resultlist);
  686. int[] boxesInfo = new int[1];
  687. byte[] labellist = new byte[1000];
  688. TimeSpan infer_start_time = new TimeSpan(DateTime.Now.Ticks);
  689. Det_ModelPredict(inputData, bmp.Width, bmp.Height, 3, results, boxesInfo, ref labellist[0]);
  690. TimeSpan infer_end_time = new TimeSpan(DateTime.Now.Ticks);
  691. string strGet = System.Text.Encoding.Default.GetString(labellist, 0, labellist.Length);
  692. string[] predict_Label_List = strGet.Split(' ');
  693. using OpenCvSharp.Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);
  694. for (int i = 0; i < boxesInfo[0]; i++)
  695. {
  696. int labelindex = Convert.ToInt32(resultlist[i * 6 + 0]);
  697. float score = resultlist[i * 6 + 1];
  698. float left = resultlist[i * 6 + 2];
  699. float top = resultlist[i * 6 + 3];
  700. float right = resultlist[i * 6 + 4]; // det -- right down
  701. float down = resultlist[i * 6 + 5];
  702. if (score > det_threshold)
  703. {
  704. int[] color_ = { (int)(color_map[(labelindex%256)*3]),
  705. (int)(color_map[(labelindex % 256) * 3 + 1]),
  706. (int)(color_map[(labelindex % 256) * 3 + 2]) };
  707. var text_size = Cv2.GetTextSize($"{predict_Label_List[i]}-{labelindex}-{score:f2}",
  708. HersheyFonts.HersheySimplex, 1, 2, out int baseline);
  709. int left_down_x = (int)left + 22;
  710. int left_down_y = (int)top + text_size.Height;
  711. Cv2.Rectangle(mat, new OpenCvSharp.Rect((int)left, (int)top, (int)right, (int)down), new OpenCvSharp.Scalar(color_[0], color_[1], color_[2]), 2, LineTypes.AntiAlias);//LineTypes.AntiAlias:反锯齿效果
  712. Cv2.PutText(mat, $"{predict_Label_List[i]}-{labelindex}-: {score:f2}", new OpenCvSharp.Point(left_down_x, left_down_y), HersheyFonts.HersheySimplex, 1, new OpenCvSharp.Scalar(color_[0], color_[1], color_[2]), 2, LineTypes.Link4);
  713. }
  714. }
  715. bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
  716. if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
  717. pictureBox1.Image = show_image;
  718. pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
  719. if (pictureBox2.Image != null) pictureBox2.Image.Dispose();
  720. pictureBox2.Image = bmp;
  721. pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
  722. TimeSpan start2end_time = infer_end_time.Subtract(infer_start_time).Duration();
  723. double cost_milliseconds = start2end_time.TotalMilliseconds;
  724. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  725. label7.Invoke(AsyncUIDelegate, new object[] { $"{cost_milliseconds:f2}" });
  726. Thread.Sleep(continue_infer_delay);
  727. }
  728. }
  729. catch (Exception e)
  730. {
  731. raise_ex_flag = 1;
  732. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  733. label7.Invoke(AsyncUIDelegate, new object[] { "0.00" });
  734. MessageBox.Show("1.请检查模型文件与模型类型是否一致!\n2.内存溢出,yml预处理有误,图片格式确保为1/3通道...", "模型运行失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  735. }
  736. isBreakInfer = 0;
  737. is_infer = 0;
  738. infer_many_img_flag = 0;
  739. if (raise_ex_flag == 0) MessageBox.Show("图片文件夹推理完成!");
  740. }
  741. private void det_infer_video_img()
  742. {
  743. is_infer = 1;
  744. byte[] color_map = get_color_map_list(256);
  745. VideoCapture capture = new VideoCapture();
  746. capture.Open(videofile);
  747. using Mat frame = new Mat();
  748. int raise_ex_flag = 0;
  749. try
  750. {
  751. while (true)
  752. {
  753. if (isBreakInfer == 1) break;
  754. capture.Read(frame);
  755. if (frame.Empty()) break;
  756. Bitmap image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(frame);
  757. if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
  758. pictureBox1.Image = image;
  759. pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
  760. image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(frame);
  761. byte[] inputData = GetBGRValues(image, out int stride);
  762. float[] resultlist = new float[600];
  763. IntPtr results = FloatToIntptr(resultlist);
  764. int[] boxesInfo = new int[1];
  765. byte[] labellist = new byte[1000];
  766. TimeSpan infer_start_time = new TimeSpan(DateTime.Now.Ticks);
  767. Det_ModelPredict(inputData, image.Width, image.Height, 3, results, boxesInfo, ref labellist[0]);
  768. TimeSpan infer_end_time = new TimeSpan(DateTime.Now.Ticks);
  769. string strGet = System.Text.Encoding.Default.GetString(labellist, 0, labellist.Length);
  770. string[] predict_Label_List = strGet.Split(' ');
  771. using OpenCvSharp.Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(image);
  772. for (int i = 0; i < boxesInfo[0]; i++)
  773. {
  774. int labelindex = Convert.ToInt32(resultlist[i * 6 + 0]);
  775. float score = resultlist[i * 6 + 1];
  776. float left = resultlist[i * 6 + 2];
  777. float top = resultlist[i * 6 + 3];
  778. float right = resultlist[i * 6 + 4];
  779. float down = resultlist[i * 6 + 5];
  780. if (score > det_threshold)
  781. {
  782. int[] color_ = { (int)(color_map[(labelindex%256)*3]),
  783. (int)(color_map[(labelindex % 256) * 3 + 1]),
  784. (int)(color_map[(labelindex % 256) * 3 + 2]) };
  785. var text_size = Cv2.GetTextSize($"{predict_Label_List[i]}-{labelindex}-{score:f2}",
  786. HersheyFonts.HersheySimplex, 1, 2, out int baseline);
  787. int left_down_x = (int)left + 22;
  788. int left_down_y = (int)top + text_size.Height;
  789. Cv2.Rectangle(mat, new OpenCvSharp.Rect((int)left, (int)top, (int)right, (int)down), new OpenCvSharp.Scalar(color_[0], color_[1], color_[2]), 2, LineTypes.AntiAlias);//LineTypes.AntiAlias:反锯齿效果
  790. Cv2.PutText(mat, $"{predict_Label_List[i]}-{labelindex}-: {score:f2}", new OpenCvSharp.Point(left_down_x, left_down_y), HersheyFonts.HersheySimplex, 1, new OpenCvSharp.Scalar(color_[0], color_[1], color_[2]), 2, LineTypes.Link4);
  791. }
  792. }
  793. image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
  794. if (pictureBox2.Image != null) pictureBox2.Image.Dispose();
  795. pictureBox2.Image = image;
  796. pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
  797. TimeSpan start2end_time = infer_end_time.Subtract(infer_start_time).Duration();
  798. double cost_milliseconds = start2end_time.TotalMilliseconds;
  799. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  800. label7.Invoke(AsyncUIDelegate, new object[] { $"{cost_milliseconds:f2}" });
  801. }
  802. }
  803. catch (Exception e)
  804. {
  805. raise_ex_flag = 1;
  806. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  807. label7.Invoke(AsyncUIDelegate, new object[] { "0.00" });
  808. MessageBox.Show("1.请检查模型文件与模型类型是否一致!\n2.内存溢出,yml预处理有误,图片格式确保为1/3通道...", "模型运行失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  809. }
  810. isBreakInfer = 0;
  811. is_infer = 0;
  812. infer_video_img_flag = 0;
  813. if (raise_ex_flag == 0) MessageBox.Show("视频推理完成!");
  814. }
  815. // Fixed size display: Short_side: 512
  816. private void cls_infer_one_img()
  817. {
  818. is_infer = 1;
  819. byte[] color_map = get_color_map_list(256);
  820. //Bitmap bmp = new Bitmap(imgfile);
  821. Bitmap bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(Cv2.ImRead(imgfile));
  822. // resize()
  823. var short_side = bmp.Width > bmp.Height ? bmp.Height : bmp.Width;
  824. double resize_scale = 512.0 / short_side;
  825. OpenCvSharp.Mat input_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);
  826. OpenCvSharp.Mat output_mat = new Mat();
  827. int new_height = (int)(bmp.Height * resize_scale);
  828. int new_width = (int)(bmp.Width * resize_scale);
  829. Cv2.Resize(input_mat, output_mat, new OpenCvSharp.Size(new_width, new_height));
  830. bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(output_mat);
  831. byte[] inputData = GetBGRValues(bmp, out int stride);
  832. float[] pre_score = new float[1];
  833. int[] pre_category_id = new int[1];
  834. byte[] pre_category = new byte[200];
  835. int raise_ex_flag = 0;
  836. try
  837. {
  838. TimeSpan infer_start_time = new TimeSpan(DateTime.Now.Ticks);
  839. Cls_ModelPredict(inputData, bmp.Width, bmp.Height, 3, ref pre_score[0], ref pre_category[0], ref pre_category_id[0]);
  840. TimeSpan infer_end_time = new TimeSpan(DateTime.Now.Ticks);
  841. string category_strGet = System.Text.Encoding.Default.GetString(pre_category, 0, pre_category.Length).Split('\0')[0];
  842. OpenCvSharp.Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);
  843. int[] color_ = { (int)(color_map[(pre_category_id[0]%256)*3]),
  844. (int)(color_map[(pre_category_id[0] % 256) * 3 + 1]),
  845. (int)(color_map[(pre_category_id[0] % 256) * 3 + 2]) };
  846. var text_size = Cv2.GetTextSize($"{category_strGet}-{pre_category_id[0]}-{pre_score[0]:f2}",
  847. HersheyFonts.HersheySimplex, 1, 2, out int baseline);
  848. int left_down_x = bmp.Width - text_size.Width;
  849. int left_down_y = text_size.Height;
  850. Cv2.PutText(mat, $"{category_strGet}-{pre_category_id[0]}-{pre_score[0]:f2}", new OpenCvSharp.Point(left_down_x, left_down_y), HersheyFonts.HersheySimplex, 1, new OpenCvSharp.Scalar(color_[0], color_[1], color_[2]), 2, LineTypes.Link4);
  851. bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
  852. if (pictureBox2.Image != null) pictureBox2.Image.Dispose();
  853. pictureBox2.Image = bmp;
  854. pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
  855. input_mat = null;
  856. output_mat = null;
  857. mat = null;
  858. inputData = null;
  859. pre_score = null;
  860. pre_category_id = null;
  861. pre_category = null;
  862. TimeSpan start2end_time = infer_end_time.Subtract(infer_start_time).Duration();
  863. double cost_milliseconds = start2end_time.TotalMilliseconds;
  864. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  865. label7.Invoke(AsyncUIDelegate, new object[] { $"{cost_milliseconds:f2}" });
  866. }
  867. catch (Exception e)
  868. {
  869. raise_ex_flag = 1;
  870. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  871. label7.Invoke(AsyncUIDelegate, new object[] { "0.00" });
  872. MessageBox.Show("1.请检查模型文件与模型类型是否一致!\n2.内存溢出,yml预处理有误,图片格式确保为1/3通道...", "模型运行失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  873. }
  874. isBreakInfer = 0;
  875. is_infer = 0;
  876. infer_one_img_flag = 0;
  877. if (raise_ex_flag == 0) MessageBox.Show("图片推理完成!");
  878. }
  879. private void cls_infer_many_img()
  880. {
  881. is_infer = 1;
  882. byte[] color_map = get_color_map_list(256);
  883. int raise_ex_flag = 0;
  884. try
  885. {
  886. foreach (string img_file in imgfiles)
  887. {
  888. if (isBreakInfer == 1) break;
  889. //Bitmap bmp = new Bitmap(img_file);
  890. Bitmap bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(Cv2.ImRead(img_file));
  891. // resize()
  892. var short_side = bmp.Width > bmp.Height ? bmp.Height : bmp.Width;
  893. double resize_scale = 512.0 / short_side;
  894. OpenCvSharp.Mat input_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);
  895. OpenCvSharp.Mat output_mat = new Mat();
  896. int new_height = (int)(bmp.Height * resize_scale);
  897. int new_width = (int)(bmp.Width * resize_scale);
  898. Cv2.Resize(input_mat, output_mat, new OpenCvSharp.Size(new_width, new_height));
  899. bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(output_mat);
  900. byte[] inputData = GetBGRValues(bmp, out int stride);
  901. float[] pre_score = new float[1];
  902. int[] pre_category_id = new int[1];
  903. byte[] pre_category = new byte[200];
  904. TimeSpan infer_start_time = new TimeSpan(DateTime.Now.Ticks);
  905. Cls_ModelPredict(inputData, bmp.Width, bmp.Height, 3, ref pre_score[0], ref pre_category[0], ref pre_category_id[0]);
  906. TimeSpan infer_end_time = new TimeSpan(DateTime.Now.Ticks);
  907. string category_strGet = System.Text.Encoding.Default.GetString(pre_category, 0, pre_category.Length).Split('\0')[0];
  908. OpenCvSharp.Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);
  909. int[] color_ = { (int)(color_map[(pre_category_id[0]%256)*3]),
  910. (int)(color_map[(pre_category_id[0] % 256) * 3 + 1]),
  911. (int)(color_map[(pre_category_id[0] % 256) * 3 + 2]) };
  912. var text_size = Cv2.GetTextSize($"{category_strGet}-{pre_category_id[0]}-:{pre_score[0]:f2}",
  913. HersheyFonts.HersheySimplex, 1, 2, out int baseline);
  914. int left_down_x = bmp.Width - text_size.Width;
  915. int left_down_y = text_size.Height;
  916. Cv2.PutText(mat, $"{category_strGet}-{pre_category_id[0]}-:{pre_score[0]:f2}", new OpenCvSharp.Point(left_down_x, left_down_y), HersheyFonts.HersheySimplex, 1, new OpenCvSharp.Scalar(color_[0], color_[1], color_[2]), 2, LineTypes.Link4);
  917. bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
  918. Bitmap show_image = new Bitmap(img_file);
  919. if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
  920. pictureBox1.Image = show_image;
  921. pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
  922. if (pictureBox2.Image != null) pictureBox2.Image.Dispose();
  923. pictureBox2.Image = bmp;
  924. pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
  925. mat = null;
  926. inputData = null;
  927. pre_score = null;
  928. pre_category_id = null;
  929. pre_category = null;
  930. TimeSpan start2end_time = infer_end_time.Subtract(infer_start_time).Duration();
  931. double cost_milliseconds = start2end_time.TotalMilliseconds;
  932. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  933. label7.Invoke(AsyncUIDelegate, new object[] { $"{cost_milliseconds:f2}" });
  934. Thread.Sleep(continue_infer_delay);
  935. }
  936. }
  937. catch (Exception e)
  938. {
  939. raise_ex_flag = 1;
  940. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  941. label7.Invoke(AsyncUIDelegate, new object[] { "0.00" });
  942. MessageBox.Show("1.请检查模型文件与模型类型是否一致!\n2.内存溢出,yml预处理有误,图片格式确保为1/3通道...", "模型运行失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  943. }
  944. isBreakInfer = 0;
  945. is_infer = 0;
  946. infer_many_img_flag = 0;
  947. if (raise_ex_flag == 0) MessageBox.Show("图片文件夹推理完成!");
  948. }
  949. private void cls_infer_video_img()
  950. {
  951. is_infer = 1;
  952. byte[] color_map = get_color_map_list(256);
  953. VideoCapture capture = new VideoCapture();
  954. capture.Open(videofile);
  955. using Mat frame = new Mat();
  956. int raise_ex_flag = 0;
  957. try
  958. {
  959. while (true)
  960. {
  961. if (isBreakInfer == 1) break;
  962. capture.Read(frame);
  963. if (frame.Empty()) break;
  964. Bitmap image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(frame);
  965. if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
  966. pictureBox1.Image = image;
  967. pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
  968. image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(frame);
  969. // resize()
  970. var short_side = image.Width > image.Height ? image.Height : image.Width;
  971. double resize_scale = 512.0 / short_side;
  972. OpenCvSharp.Mat input_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(image);
  973. OpenCvSharp.Mat output_mat = new Mat();
  974. int new_height = (int)(image.Height * resize_scale);
  975. int new_width = (int)(image.Width * resize_scale);
  976. Cv2.Resize(input_mat, output_mat, new OpenCvSharp.Size(new_width, new_height));
  977. image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(output_mat);
  978. byte[] inputData = GetBGRValues(image, out int stride);
  979. float[] pre_score = new float[1];
  980. int[] pre_category_id = new int[1];
  981. byte[] pre_category = new byte[200];
  982. TimeSpan infer_start_time = new TimeSpan(DateTime.Now.Ticks);
  983. Cls_ModelPredict(inputData, image.Width, image.Height, 3, ref pre_score[0], ref pre_category[0], ref pre_category_id[0]);
  984. TimeSpan infer_end_time = new TimeSpan(DateTime.Now.Ticks);
  985. string category_strGet = System.Text.Encoding.Default.GetString(pre_category, 0, pre_category.Length).Split('\0')[0];
  986. OpenCvSharp.Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(image);
  987. int[] color_ = { (int)(color_map[(pre_category_id[0]%256)*3]),
  988. (int)(color_map[(pre_category_id[0] % 256) * 3 + 1]),
  989. (int)(color_map[(pre_category_id[0] % 256) * 3 + 2]) };
  990. var text_size = Cv2.GetTextSize($"{category_strGet}-{pre_category_id[0]}-:{pre_score[0]:f2}",
  991. HersheyFonts.HersheySimplex, 1, 2, out int baseline);
  992. int left_down_x = image.Width - text_size.Width;
  993. int left_down_y = text_size.Height;
  994. Cv2.PutText(mat, $"{category_strGet}-{pre_category_id[0]}-:{pre_score[0]:f2}", new OpenCvSharp.Point(left_down_x, left_down_y), HersheyFonts.HersheySimplex, 1, new OpenCvSharp.Scalar(color_[0], color_[1], color_[2]), 2, LineTypes.Link4);
  995. image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
  996. pictureBox2.Image = image;
  997. pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
  998. mat = null;
  999. inputData = null;
  1000. pre_score = null;
  1001. pre_category_id = null;
  1002. pre_category = null;
  1003. TimeSpan start2end_time = infer_end_time.Subtract(infer_start_time).Duration();
  1004. double cost_milliseconds = start2end_time.TotalMilliseconds;
  1005. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  1006. label7.Invoke(AsyncUIDelegate, new object[] { $"{cost_milliseconds:f2}" });
  1007. }
  1008. }
  1009. catch (Exception e)
  1010. {
  1011. raise_ex_flag = 1;
  1012. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  1013. label7.Invoke(AsyncUIDelegate, new object[] { "0.00" });
  1014. MessageBox.Show("1.请检查模型文件与模型类型是否一致!\n2.内存溢出,yml预处理有误,图片格式确保为1/3通道...", "模型运行失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  1015. }
  1016. isBreakInfer = 0;
  1017. // DestructModel();
  1018. is_infer = 0;
  1019. infer_video_img_flag = 0;
  1020. if (raise_ex_flag == 0) MessageBox.Show("视频推理完成!");
  1021. }
  1022. // Fixed size display: Short_side: 512
  1023. private void seg_infer_one_img()
  1024. {
  1025. is_infer = 1;
  1026. byte[] color_map = get_color_map_list(256);
  1027. //Bitmap origin_bmp = new Bitmap(imgfile);
  1028. Bitmap origin_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(Cv2.ImRead(imgfile));
  1029. Bitmap input_bmp = null;
  1030. // resize()
  1031. OpenCvSharp.Mat input_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(origin_bmp);
  1032. OpenCvSharp.Mat output_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(origin_bmp);
  1033. Cv2.Resize(input_mat, output_mat, new OpenCvSharp.Size(512, 512));
  1034. input_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(output_mat);
  1035. input_mat = null;
  1036. output_mat = null;
  1037. byte[] inputData = GetBGRValues(input_bmp, out int stride);
  1038. byte[] output_map = new byte[input_bmp.Height * input_bmp.Width];
  1039. int raise_ex_flag = 0;
  1040. try
  1041. {
  1042. TimeSpan infer_start_time = new TimeSpan(DateTime.Now.Ticks);
  1043. Seg_ModelPredict(inputData, input_bmp.Width, input_bmp.Height, 3, ref output_map[0]);
  1044. TimeSpan infer_end_time = new TimeSpan(DateTime.Now.Ticks);
  1045. input_bmp = CreateBitmap(output_map, input_bmp.Width, input_bmp.Height, color_map);
  1046. input_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(input_bmp);
  1047. output_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(input_bmp);
  1048. Cv2.Resize(input_mat, output_mat, new OpenCvSharp.Size(origin_bmp.Width, origin_bmp.Height));
  1049. input_mat = null;
  1050. input_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(origin_bmp);
  1051. //OpenCvSharp.Mat add_mat = new Mat();
  1052. Cv2.AddWeighted(output_mat, 1.0, input_mat, 0.35, 1, output_mat);
  1053. input_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(output_mat);
  1054. if (pictureBox2.Image != null) pictureBox2.Image.Dispose();
  1055. pictureBox2.Image = input_bmp;
  1056. pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
  1057. TimeSpan start2end_time = infer_end_time.Subtract(infer_start_time).Duration();
  1058. double cost_milliseconds = start2end_time.TotalMilliseconds;
  1059. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  1060. label7.Invoke(AsyncUIDelegate, new object[] { $"{cost_milliseconds:f2}" });
  1061. }
  1062. catch (Exception e)
  1063. {
  1064. raise_ex_flag = 1;
  1065. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  1066. label7.Invoke(AsyncUIDelegate, new object[] { "0.00" });
  1067. MessageBox.Show("1.请检查模型文件与模型类型是否一致!\n2.内存溢出,yml预处理有误,图片格式确保为1/3通道...", "模型运行失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  1068. }
  1069. isBreakInfer = 0;
  1070. is_infer = 0;
  1071. infer_one_img_flag = 0;
  1072. if (raise_ex_flag == 0) MessageBox.Show("图片推理完成!");
  1073. }
  1074. private void seg_infer_many_img()
  1075. {
  1076. is_infer = 1;
  1077. byte[] color_map = get_color_map_list(256);
  1078. int raise_ex_flag = 0;
  1079. try
  1080. {
  1081. foreach (string img_file in imgfiles)
  1082. {
  1083. if (isBreakInfer == 1) break;
  1084. Bitmap origin_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(Cv2.ImRead(img_file));
  1085. Bitmap input_bmp = null;
  1086. // resize()
  1087. OpenCvSharp.Mat input_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(origin_bmp);
  1088. OpenCvSharp.Mat output_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(origin_bmp);
  1089. Cv2.Resize(input_mat, output_mat, new OpenCvSharp.Size(512, 512));
  1090. input_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(output_mat);
  1091. input_mat = null;
  1092. output_mat = null;
  1093. byte[] inputData = GetBGRValues(input_bmp, out int stride);
  1094. byte[] output_map = new byte[input_bmp.Height * input_bmp.Width];
  1095. TimeSpan infer_start_time = new TimeSpan(DateTime.Now.Ticks);
  1096. Seg_ModelPredict(inputData, input_bmp.Width, input_bmp.Height, 3, ref output_map[0]);
  1097. TimeSpan infer_end_time = new TimeSpan(DateTime.Now.Ticks);
  1098. input_bmp = CreateBitmap(output_map, input_bmp.Width, input_bmp.Height, color_map);
  1099. input_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(input_bmp);
  1100. output_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(input_bmp);
  1101. Cv2.Resize(input_mat, output_mat, new OpenCvSharp.Size(origin_bmp.Width, origin_bmp.Height));
  1102. input_mat = null;
  1103. input_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(origin_bmp);
  1104. Cv2.AddWeighted(output_mat, 1.0, input_mat, 0.35, 1, output_mat);
  1105. input_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(output_mat);
  1106. if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
  1107. pictureBox1.Image = origin_bmp;
  1108. pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
  1109. if (pictureBox2.Image != null) pictureBox2.Image.Dispose();
  1110. pictureBox2.Image = input_bmp;
  1111. pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
  1112. TimeSpan start2end_time = infer_end_time.Subtract(infer_start_time).Duration();
  1113. double cost_milliseconds = start2end_time.TotalMilliseconds;
  1114. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  1115. label7.Invoke(AsyncUIDelegate, new object[] { $"{cost_milliseconds:f2}" });
  1116. Thread.Sleep(continue_infer_delay);
  1117. }
  1118. }
  1119. catch (Exception e)
  1120. {
  1121. raise_ex_flag = 1;
  1122. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  1123. label7.Invoke(AsyncUIDelegate, new object[] { "0.00" });
  1124. MessageBox.Show("1.请检查模型文件与模型类型是否一致!\n2.内存溢出,yml预处理有误,图片格式确保为1/3通道...", "模型运行失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  1125. }
  1126. isBreakInfer = 0;
  1127. is_infer = 0;
  1128. infer_many_img_flag = 0;
  1129. if (raise_ex_flag == 0) MessageBox.Show("图片文件夹推理完成!");
  1130. }
  1131. private void seg_infer_video_img()
  1132. {
  1133. is_infer = 1;
  1134. byte[] color_map = get_color_map_list(256);
  1135. VideoCapture capture = new VideoCapture();
  1136. capture.Open(videofile);
  1137. using Mat frame = new Mat();
  1138. int raise_ex_flag = 0;
  1139. try
  1140. {
  1141. while (true)
  1142. {
  1143. if (isBreakInfer == 1) break;
  1144. capture.Read(frame);
  1145. if (frame.Empty()) break;
  1146. Bitmap origin_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(frame);
  1147. Bitmap input_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(frame);
  1148. // resize()
  1149. OpenCvSharp.Mat input_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(origin_bmp);
  1150. OpenCvSharp.Mat output_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(origin_bmp);
  1151. Cv2.Resize(input_mat, output_mat, new OpenCvSharp.Size(512, 512));
  1152. input_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(output_mat);
  1153. input_mat = null;
  1154. output_mat = null;
  1155. byte[] inputData = GetBGRValues(input_bmp, out int stride);
  1156. byte[] output_map = new byte[input_bmp.Height * input_bmp.Width];
  1157. TimeSpan infer_start_time = new TimeSpan(DateTime.Now.Ticks);
  1158. Seg_ModelPredict(inputData, input_bmp.Width, input_bmp.Height, 3, ref output_map[0]);
  1159. TimeSpan infer_end_time = new TimeSpan(DateTime.Now.Ticks);
  1160. input_bmp = CreateBitmap(output_map, input_bmp.Width, input_bmp.Height, color_map);
  1161. input_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(input_bmp);
  1162. output_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(input_bmp);
  1163. Cv2.Resize(input_mat, output_mat, new OpenCvSharp.Size(origin_bmp.Width, origin_bmp.Height));
  1164. input_mat = null;
  1165. input_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(origin_bmp);
  1166. Cv2.AddWeighted(output_mat, 1.0, input_mat, 0.35, 1, output_mat);
  1167. input_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(output_mat);
  1168. if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
  1169. pictureBox1.Image = origin_bmp;
  1170. pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
  1171. if (pictureBox2.Image != null) pictureBox2.Image.Dispose();
  1172. pictureBox2.Image = input_bmp;
  1173. pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
  1174. TimeSpan start2end_time = infer_end_time.Subtract(infer_start_time).Duration();
  1175. double cost_milliseconds = start2end_time.TotalMilliseconds;
  1176. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  1177. label7.Invoke(AsyncUIDelegate, new object[] { $"{cost_milliseconds:f2}" });
  1178. }
  1179. }
  1180. catch (Exception e)
  1181. {
  1182. raise_ex_flag = 1;
  1183. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  1184. label7.Invoke(AsyncUIDelegate, new object[] { "0.00" });
  1185. MessageBox.Show("1.请检查模型文件与模型类型是否一致!\n2.内存溢出,yml预处理有误,图片格式确保为1/3通道...", "模型运行失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  1186. }
  1187. isBreakInfer = 0;
  1188. // DestructModel();
  1189. is_infer = 0;
  1190. infer_video_img_flag = 0;
  1191. if (raise_ex_flag == 0) MessageBox.Show("视频推理完成!");
  1192. }
  1193. // Maskrcnn detection single picture - GPU reasoning is normal
  1194. private void mask_infer_one_img()
  1195. {
  1196. is_infer = 1;
  1197. byte[] color_map = get_color_map_list(256);
  1198. Bitmap origin_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(Cv2.ImRead(imgfile));
  1199. Bitmap input_bmp = null;
  1200. // resize()
  1201. OpenCvSharp.Mat input_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(origin_bmp);
  1202. OpenCvSharp.Mat output_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(origin_bmp);
  1203. input_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(output_mat);
  1204. byte[] inputData = GetBGRValues(origin_bmp, out int stride);
  1205. float[] resultlist = new float[600];
  1206. IntPtr results = FloatToIntptr(resultlist);
  1207. byte[] mask_results = new byte[input_bmp.Height * input_bmp.Width];
  1208. int[] boxesInfo = new int[1];
  1209. byte[] labellist = new byte[1000];
  1210. int raise_ex_flag = 0;
  1211. try
  1212. {
  1213. TimeSpan infer_start_time = new TimeSpan(DateTime.Now.Ticks);
  1214. Mask_ModelPredict(inputData, input_bmp.Width, input_bmp.Height, 3, results, ref mask_results[0], boxesInfo, ref labellist[0]);
  1215. TimeSpan infer_end_time = new TimeSpan(DateTime.Now.Ticks);
  1216. input_bmp = CreateBitmap(mask_results, input_bmp.Width, input_bmp.Height, color_map);
  1217. output_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(input_bmp);
  1218. input_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(origin_bmp);
  1219. Cv2.AddWeighted(output_mat, 0.65, input_mat, 0.35, 1, output_mat);
  1220. input_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(output_mat);
  1221. string strGet = System.Text.Encoding.Default.GetString(labellist, 0, labellist.Length);
  1222. string[] predict_Label_List = strGet.Split(' ');
  1223. using OpenCvSharp.Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(input_bmp);
  1224. for (int i = 0; i < boxesInfo[0]; i++)
  1225. {
  1226. int labelindex = Convert.ToInt32(resultlist[i * 6 + 0]);
  1227. float score = resultlist[i * 6 + 1];
  1228. float left = resultlist[i * 6 + 2];
  1229. float top = resultlist[i * 6 + 3];
  1230. float right = resultlist[i * 6 + 4];
  1231. float down = resultlist[i * 6 + 5];
  1232. if (score > det_threshold)
  1233. {
  1234. labelindex += 1; // Mask rcnn contains background, so add 1
  1235. int[] color_ = { (int)(color_map[(labelindex%256)*3]),
  1236. (int)(color_map[(labelindex % 256) * 3 + 1]),
  1237. (int)(color_map[(labelindex % 256) * 3 + 2]) };
  1238. labelindex -= 1;
  1239. var text_size = Cv2.GetTextSize($"{predict_Label_List[i]}-{labelindex}-{score:f2}",
  1240. HersheyFonts.HersheySimplex, 1, 2, out int baseline);
  1241. int left_down_x = (int)left + 22;
  1242. int left_down_y = (int)top + text_size.Height;
  1243. Cv2.Rectangle(mat, new OpenCvSharp.Rect((int)left, (int)top, (int)right, (int)down), new OpenCvSharp.Scalar(color_[0], color_[1], color_[2]), 2, LineTypes.AntiAlias);//LineTypes.AntiAlias:反锯齿效果
  1244. Cv2.PutText(mat, $"{predict_Label_List[i]}-{labelindex}-: {score:f2}", new OpenCvSharp.Point(left_down_x, left_down_y), HersheyFonts.HersheySimplex, 1, new OpenCvSharp.Scalar(color_[0], color_[1], color_[2]), 2, LineTypes.Link4);
  1245. }
  1246. }
  1247. input_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
  1248. if (pictureBox2.Image != null) pictureBox2.Image.Dispose();
  1249. pictureBox2.Image = input_bmp;
  1250. pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
  1251. TimeSpan start2end_time = infer_end_time.Subtract(infer_start_time).Duration();
  1252. double cost_milliseconds = start2end_time.TotalMilliseconds;
  1253. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  1254. label7.Invoke(AsyncUIDelegate, new object[] { $"{cost_milliseconds:f2}" });
  1255. }
  1256. catch (Exception e)
  1257. {
  1258. raise_ex_flag = 1;
  1259. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  1260. label7.Invoke(AsyncUIDelegate, new object[] { "0.00" });
  1261. MessageBox.Show("1.请检查模型文件与模型类型是否一致!\n2.内存溢出,yml预处理有误,图片格式确保为1/3通道...", "模型运行失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  1262. }
  1263. isBreakInfer = 0;
  1264. is_infer = 0;
  1265. infer_one_img_flag = 0;
  1266. if (raise_ex_flag == 0) MessageBox.Show("图片推理完成!");
  1267. }
  1268. private void mask_infer_many_img()
  1269. {
  1270. is_infer = 1;
  1271. byte[] color_map = get_color_map_list(256);
  1272. int raise_ex_flag = 0;
  1273. try
  1274. {
  1275. foreach (string img_file in imgfiles)
  1276. {
  1277. if (isBreakInfer == 1) break;
  1278. Bitmap origin_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(Cv2.ImRead(img_file));
  1279. Bitmap input_bmp = null;
  1280. // resize()
  1281. OpenCvSharp.Mat input_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(origin_bmp);
  1282. OpenCvSharp.Mat output_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(origin_bmp);
  1283. input_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(output_mat);
  1284. byte[] inputData = GetBGRValues(origin_bmp, out int stride);
  1285. float[] resultlist = new float[600];
  1286. IntPtr results = FloatToIntptr(resultlist);
  1287. byte[] mask_results = new byte[input_bmp.Height * input_bmp.Width];
  1288. int[] boxesInfo = new int[1];
  1289. byte[] labellist = new byte[1000];
  1290. TimeSpan infer_start_time = new TimeSpan(DateTime.Now.Ticks);
  1291. Mask_ModelPredict(inputData, input_bmp.Width, input_bmp.Height, 3, results, ref mask_results[0], boxesInfo, ref labellist[0]);
  1292. TimeSpan infer_end_time = new TimeSpan(DateTime.Now.Ticks);
  1293. input_bmp = CreateBitmap(mask_results, input_bmp.Width, input_bmp.Height, color_map);
  1294. output_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(input_bmp);
  1295. input_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(origin_bmp);
  1296. Cv2.AddWeighted(output_mat, 1.0, input_mat, 0.35, 1, output_mat);
  1297. input_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(output_mat);
  1298. string strGet = System.Text.Encoding.Default.GetString(labellist, 0, labellist.Length);
  1299. string[] predict_Label_List = strGet.Split(' ');
  1300. using OpenCvSharp.Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(input_bmp);
  1301. for (int i = 0; i < boxesInfo[0]; i++)
  1302. {
  1303. int labelindex = Convert.ToInt32(resultlist[i * 6 + 0]);
  1304. float score = resultlist[i * 6 + 1];
  1305. float left = resultlist[i * 6 + 2];
  1306. float top = resultlist[i * 6 + 3];
  1307. float right = resultlist[i * 6 + 4];
  1308. float down = resultlist[i * 6 + 5];
  1309. if (score > det_threshold)
  1310. {
  1311. labelindex += 1;
  1312. int[] color_ = { (int)(color_map[(labelindex%256)*3]),
  1313. (int)(color_map[(labelindex % 256) * 3 + 1]),
  1314. (int)(color_map[(labelindex % 256) * 3 + 2]) };
  1315. labelindex -= 1;
  1316. var text_size = Cv2.GetTextSize($"{predict_Label_List[i]}-{labelindex}-{score:f2}",
  1317. HersheyFonts.HersheySimplex, 1, 2, out int baseline);
  1318. int left_down_x = (int)left + 22;
  1319. int left_down_y = (int)top + text_size.Height;
  1320. Cv2.Rectangle(mat, new OpenCvSharp.Rect((int)left, (int)top, (int)right, (int)down), new OpenCvSharp.Scalar(color_[0], color_[1], color_[2]), 2, LineTypes.AntiAlias);//LineTypes.AntiAlias:反锯齿效果
  1321. Cv2.PutText(mat, $"{predict_Label_List[i]}-{labelindex}-: {score:f2}", new OpenCvSharp.Point(left_down_x, left_down_y), HersheyFonts.HersheySimplex, 1, new OpenCvSharp.Scalar(color_[0], color_[1], color_[2]), 2, LineTypes.Link4);
  1322. }
  1323. }
  1324. if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
  1325. pictureBox1.Image = origin_bmp;
  1326. pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
  1327. input_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
  1328. if (pictureBox2.Image != null) pictureBox2.Image.Dispose();
  1329. pictureBox2.Image = input_bmp;
  1330. pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
  1331. TimeSpan start2end_time = infer_end_time.Subtract(infer_start_time).Duration();
  1332. double cost_milliseconds = start2end_time.TotalMilliseconds;
  1333. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  1334. label7.Invoke(AsyncUIDelegate, new object[] { $"{cost_milliseconds:f2}" });
  1335. Thread.Sleep(continue_infer_delay);
  1336. }
  1337. }
  1338. catch (Exception e)
  1339. {
  1340. raise_ex_flag = 1;
  1341. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  1342. label7.Invoke(AsyncUIDelegate, new object[] { "0.00" });
  1343. MessageBox.Show("1.请检查模型文件与模型类型是否一致!\n2.内存溢出,yml预处理有误,图片格式确保为1/3通道...", "模型运行失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  1344. }
  1345. isBreakInfer = 0;
  1346. is_infer = 0;
  1347. infer_many_img_flag = 0;
  1348. if (raise_ex_flag == 0) MessageBox.Show("图片文件夹推理完成!");
  1349. }
  1350. private void mask_infer_video_img()
  1351. {
  1352. is_infer = 1;
  1353. byte[] color_map = get_color_map_list(256);
  1354. VideoCapture capture = new VideoCapture();
  1355. capture.Open(videofile);
  1356. using Mat frame = new Mat();
  1357. int raise_ex_flag = 0;
  1358. try
  1359. {
  1360. while (true)
  1361. {
  1362. if (isBreakInfer == 1) break;
  1363. capture.Read(frame);
  1364. if (frame.Empty()) break;
  1365. Bitmap origin_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(frame);
  1366. Bitmap input_bmp = null;
  1367. OpenCvSharp.Mat input_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(origin_bmp);
  1368. OpenCvSharp.Mat output_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(origin_bmp);
  1369. input_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(output_mat);
  1370. byte[] inputData = GetBGRValues(origin_bmp, out int stride);
  1371. float[] resultlist = new float[600];
  1372. IntPtr results = FloatToIntptr(resultlist);
  1373. byte[] mask_results = new byte[input_bmp.Height * input_bmp.Width];
  1374. int[] boxesInfo = new int[1];
  1375. byte[] labellist = new byte[1000];
  1376. TimeSpan infer_start_time = new TimeSpan(DateTime.Now.Ticks);
  1377. Mask_ModelPredict(inputData, input_bmp.Width, input_bmp.Height, 3, results, ref mask_results[0], boxesInfo, ref labellist[0]);
  1378. TimeSpan infer_end_time = new TimeSpan(DateTime.Now.Ticks);
  1379. input_bmp = CreateBitmap(mask_results, input_bmp.Width, input_bmp.Height, color_map);
  1380. output_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(input_bmp);
  1381. input_mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(origin_bmp);
  1382. Cv2.AddWeighted(output_mat, 1.0, input_mat, 0.35, 1, output_mat);
  1383. input_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(output_mat);
  1384. string strGet = System.Text.Encoding.Default.GetString(labellist, 0, labellist.Length);
  1385. string[] predict_Label_List = strGet.Split(' ');
  1386. using OpenCvSharp.Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(input_bmp);
  1387. for (int i = 0; i < boxesInfo[0]; i++)
  1388. {
  1389. int labelindex = Convert.ToInt32(resultlist[i * 6 + 0]);
  1390. float score = resultlist[i * 6 + 1];
  1391. float left = resultlist[i * 6 + 2];
  1392. float top = resultlist[i * 6 + 3];
  1393. float right = resultlist[i * 6 + 4];
  1394. float down = resultlist[i * 6 + 5];
  1395. if (score > det_threshold)
  1396. {
  1397. labelindex += 1;
  1398. int[] color_ = { (int)(color_map[(labelindex%256)*3]),
  1399. (int)(color_map[(labelindex % 256) * 3 + 1]),
  1400. (int)(color_map[(labelindex % 256) * 3 + 2]) };
  1401. labelindex -= 1;
  1402. var text_size = Cv2.GetTextSize($"{predict_Label_List[i]}-{labelindex}-{score:f2}",
  1403. HersheyFonts.HersheySimplex, 1, 2, out int baseline);
  1404. int left_down_x = (int)left + 22;
  1405. int left_down_y = (int)top + text_size.Height;
  1406. Cv2.Rectangle(mat, new OpenCvSharp.Rect((int)left, (int)top, (int)right, (int)down), new OpenCvSharp.Scalar(color_[0], color_[1], color_[2]), 2, LineTypes.AntiAlias);//LineTypes.AntiAlias:反锯齿效果
  1407. Cv2.PutText(mat, $"{predict_Label_List[i]}-{labelindex}-: {score:f2}", new OpenCvSharp.Point(left_down_x, left_down_y), HersheyFonts.HersheySimplex, 1, new OpenCvSharp.Scalar(color_[0], color_[1], color_[2]), 2, LineTypes.Link4);
  1408. }
  1409. }
  1410. if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
  1411. pictureBox1.Image = origin_bmp;
  1412. pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
  1413. input_bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
  1414. if (pictureBox2.Image != null) pictureBox2.Image.Dispose();
  1415. pictureBox2.Image = input_bmp;
  1416. pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
  1417. TimeSpan start2end_time = infer_end_time.Subtract(infer_start_time).Duration();
  1418. double cost_milliseconds = start2end_time.TotalMilliseconds;
  1419. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  1420. label7.Invoke(AsyncUIDelegate, new object[] { $"{cost_milliseconds:f2}" });
  1421. }
  1422. }
  1423. catch (Exception e)
  1424. {
  1425. raise_ex_flag = 1;
  1426. Action<String> AsyncUIDelegate = delegate (string n) { label7.Text = n; };
  1427. label7.Invoke(AsyncUIDelegate, new object[] { "0.00" });
  1428. MessageBox.Show("1.Please check if the model file is consistent with the model type!\n2.Memory overflow, YML pretreatment incorrectly, the picture format is ensured as 1/3 channel...", "Model run failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
  1429. }
  1430. isBreakInfer = 0;
  1431. is_infer = 0;
  1432. infer_video_img_flag = 0;
  1433. if (raise_ex_flag == 0) MessageBox.Show("视频推理完成!");
  1434. }
  1435. /**********************************************************************/
  1436. /***************** 7.Part of the reasoning component function ***************/
  1437. /**********************************************************************/
  1438. /// <summary>
  1439. /// Read the data from the memory stream
  1440. /// </summary>
  1441. /// <param name="curStream"></param>
  1442. /// <param name="startPosition"></param>
  1443. /// <param name="length"></param>
  1444. /// <returns></returns>
  1445. public static int ReadData(MemoryStream curStream, int startPosition, int length)
  1446. {
  1447. int result = -1;
  1448. byte[] tempData = new byte[length];
  1449. curStream.Position = startPosition;
  1450. curStream.Read(tempData, 0, length);
  1451. result = BitConverter.ToInt32(tempData, 0);
  1452. return result;
  1453. }
  1454. /// <summary>
  1455. /// Use Byte [] data to generate three-way BMP bitmap
  1456. /// </summary>
  1457. /// <param name="originalImageData"></param>
  1458. /// <param name="originalWidth"></param>
  1459. /// <param name="originalHeight"></param>
  1460. /// <returns></returns>
  1461. public static Bitmap CreateBitmap(byte[] originalImageData, int originalWidth, int originalHeight, byte[] color_map)
  1462. {
  1463. Bitmap resultBitmap = new Bitmap(originalWidth, originalHeight, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
  1464. MemoryStream curImageStream = new MemoryStream();
  1465. resultBitmap.Save(curImageStream, System.Drawing.Imaging.ImageFormat.Bmp);
  1466. curImageStream.Flush();
  1467. int curPadNum = ((originalWidth * 8 + 31) / 32 * 4) - originalWidth;
  1468. int bitmapDataSize = ((originalWidth * 8 + 31) / 32 * 4) * originalHeight;
  1469. int dataOffset = ReadData(curImageStream, 10, 4);
  1470. int paletteStart = 54;
  1471. int paletteEnd = dataOffset;
  1472. int color = 0;
  1473. for (int i = paletteStart; i < paletteEnd; i += 4)
  1474. {
  1475. byte[] tempColor = new byte[4];
  1476. tempColor[0] = (byte)color;
  1477. tempColor[1] = (byte)color;
  1478. tempColor[2] = (byte)color;
  1479. tempColor[3] = (byte)0;
  1480. color++;
  1481. curImageStream.Position = i;
  1482. curImageStream.Write(tempColor, 0, 4);
  1483. }
  1484. byte[] destImageData = new byte[bitmapDataSize];
  1485. int destWidth = originalWidth + curPadNum;
  1486. for (int originalRowIndex = originalHeight - 1; originalRowIndex >= 0; originalRowIndex--)
  1487. {
  1488. int destRowIndex = originalHeight - originalRowIndex - 1;
  1489. for (int dataIndex = 0; dataIndex < originalWidth; dataIndex++)
  1490. {
  1491. destImageData[destRowIndex * destWidth + dataIndex] = originalImageData[originalRowIndex * originalWidth + dataIndex];
  1492. }
  1493. }
  1494. curImageStream.Position = dataOffset;
  1495. curImageStream.Write(destImageData, 0, bitmapDataSize);
  1496. curImageStream.Flush();
  1497. resultBitmap = new Bitmap(curImageStream);
  1498. resultBitmap = transForm8to24(resultBitmap, color_map);
  1499. return resultBitmap;
  1500. }
  1501. // Implement Bitmap single channel to three-channel (split generation mask image (single channel) ==> RGB image)
  1502. public static Bitmap transForm8to24(Bitmap bmp, byte[] color_map)
  1503. {
  1504. System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height);
  1505. System.Drawing.Imaging.BitmapData bitmapData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);
  1506. int size8 = bitmapData.Stride * bmp.Height;
  1507. byte[] grayValues = new byte[size8];
  1508. Bitmap TempBmp = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format24bppRgb);
  1509. BitmapData TempBmpData = TempBmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
  1510. int stride = TempBmpData.Stride;
  1511. int offset = stride - TempBmp.Width;
  1512. IntPtr iptr = TempBmpData.Scan0;
  1513. int scanBytes = stride * TempBmp.Height;
  1514. byte[] pixelValues = new byte[scanBytes];
  1515. System.Runtime.InteropServices.Marshal.Copy(bitmapData.Scan0, grayValues, 0, size8);
  1516. for (int i = 0; i < bmp.Height; i++)
  1517. {
  1518. for (int j = 0; j < bitmapData.Stride; j++)
  1519. {
  1520. if (j >= bmp.Width)
  1521. continue;
  1522. int indexSrc = i * bitmapData.Stride + j;
  1523. int realIndex = i * TempBmpData.Stride + j * 3;
  1524. // color_id:The result of predicting
  1525. int color_id = (int)grayValues[indexSrc] % 256;
  1526. if (color_id == 0) // Segmentation Category 1 corresponds to 1, and the background is often 0, so it will be placed in [0, 0, 0] here.
  1527. {
  1528. pixelValues[realIndex] = 0;
  1529. pixelValues[realIndex + 1] = 0;
  1530. pixelValues[realIndex + 2] = 0;
  1531. }
  1532. else
  1533. {
  1534. pixelValues[realIndex] = color_map[color_id * 3];
  1535. pixelValues[realIndex + 1] = color_map[color_id * 3 + 1];
  1536. pixelValues[realIndex + 2] = color_map[color_id * 3 + 2];
  1537. }
  1538. }
  1539. }
  1540. System.Runtime.InteropServices.Marshal.Copy(pixelValues, 0, iptr, scanBytes);
  1541. TempBmp.UnlockBits(TempBmpData);
  1542. bmp.UnlockBits(bitmapData);
  1543. return TempBmp;
  1544. }
  1545. // RGB value collection of pseudo color map (color_map)
  1546. private byte[] get_color_map_list(int num_classes = 256)
  1547. {
  1548. num_classes += 1;
  1549. byte[] color_map = new byte[num_classes * 3];
  1550. for (int i = 0; i < num_classes; i++)
  1551. {
  1552. int j = 0;
  1553. int lab = i;
  1554. while (lab != 0)
  1555. {
  1556. color_map[i * 3] |= (byte)(((lab >> 0) & 1) << (7 - j));
  1557. color_map[i * 3 + 1] |= (byte)(((lab >> 1) & 1) << (7 - j));
  1558. color_map[i * 3 + 2] |= (byte)(((lab >> 2) & 1) << (7 - j));
  1559. j += 1;
  1560. lab >>= 3;
  1561. }
  1562. }
  1563. color_map = color_map.Skip(3).ToArray();
  1564. return color_map;
  1565. }
  1566. /// <summary>
  1567. /// Get all files in the directory or specify file type file (contain all subfolders)
  1568. /// </summary>
  1569. /// <param name="path">Folder path</param>
  1570. /// <param name="extName">Extension can be multiple eg: .mp3.wma.rm</param>
  1571. /// <returns>List<FileInfo></returns>
  1572. public static List<FileInfo> getFile(string path, string extName, List<FileInfo> lst)
  1573. {
  1574. try
  1575. {
  1576. DirectoryInfo fdir = new DirectoryInfo(path);
  1577. FileInfo[] file = fdir.GetFiles();
  1578. //FileInfo[] file = Directory.GetFiles(path);
  1579. if (file.Length != 0)
  1580. {
  1581. foreach (FileInfo f in file)
  1582. {
  1583. if (extName.ToLower().IndexOf(f.Extension.ToLower()) >= 0)
  1584. {
  1585. lst.Add(f);
  1586. }
  1587. }
  1588. }
  1589. return lst;
  1590. }
  1591. catch (Exception ex)
  1592. {
  1593. throw ex;
  1594. }
  1595. }
  1596. // Convert BTIMAP class to Byte [] class function
  1597. public static byte[] GetBGRValues(Bitmap bmp, out int stride)
  1598. {
  1599. var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
  1600. var bmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat);
  1601. stride = bmpData.Stride;
  1602. var rowBytes = bmpData.Width * Image.GetPixelFormatSize(bmp.PixelFormat) / 8;
  1603. var imgBytes = bmp.Height * rowBytes;
  1604. byte[] rgbValues = new byte[imgBytes];
  1605. IntPtr ptr = bmpData.Scan0;
  1606. for (var i = 0; i < bmp.Height; i++)
  1607. {
  1608. Marshal.Copy(ptr, rgbValues, i * rowBytes, rowBytes);
  1609. ptr += bmpData.Stride;
  1610. }
  1611. bmp.UnlockBits(bmpData);
  1612. return rgbValues;
  1613. }
  1614. // Creates an IntPtr pointer to a float array type
  1615. public static IntPtr FloatToIntptr(float[] bytes)
  1616. {
  1617. GCHandle hObject = GCHandle.Alloc(bytes, GCHandleType.Pinned);
  1618. return hObject.AddrOfPinnedObject();
  1619. }
  1620. // Check if the Maskrcnn model is started on the GPU - only supports GPU reasoning, because the memory takes up,
  1621. // the CPU may overflow, resulting in unable to construct
  1622. public static bool CheckMaskRCNN_workOnGpu(string model_type, bool use_gpu)
  1623. {
  1624. if (model_type == "mask")
  1625. {
  1626. if (use_gpu == false)
  1627. return false;
  1628. }
  1629. return true;
  1630. }
  1631. }
  1632. }