AI_HttpClient.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. #define cxx_server
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.Net.Http.Headers;
  10. using System.Runtime.InteropServices.ComTypes;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using Newtonsoft.Json;
  15. using OpenCvSharp;
  16. using System.Drawing;
  17. using OpenCvSharp.Extensions;
  18. using Newtonsoft.Json.Linq;
  19. using System.Runtime.InteropServices;
  20. using System.Security.Policy;
  21. using static OpenCvSharp.XImgProc.CvXImgProc;
  22. namespace OTSModelSharp.ServiceCenter
  23. {
  24. public class class_result
  25. {
  26. public string Result { get; set; }
  27. public float Confidence { get; set; }
  28. }
  29. public class AI_HttpClient
  30. {
  31. /// <summary>
  32. /// 从分割模型获取二值图
  33. /// </summary>
  34. /// <param name="baseUrl">包括ip地址端口号</param>
  35. /// <param name="input">输入mat 3通道 bgr格式</param>
  36. /// <param name="output">输出mat 灰度图</param>
  37. /// <param name="catagory">模型类别和模型配置文件对应</param>
  38. /// <param name="item">模型序号和模型配置文件对应</param>
  39. /// <param name="filename">input mat 原图完整路径</param>
  40. public static void AI_SegmentImage(string baseUrl, Mat input, ref Mat output, int catagory = 1000, int item = 1, string filename = "1.jpg")
  41. {
  42. #if cxx_server
  43. AI_SegmentImage_cxx(baseUrl, input, ref output, catagory, item, filename);
  44. #else
  45. AI_SegmentImage_cshape(baseUrl, input, ref output, catagory, item, filename);
  46. #endif
  47. }
  48. /// <summary>
  49. /// 从模型获得分类结果 需做进一步筛选获得分类
  50. /// </summary>
  51. /// <param name="baseUrl"></param>
  52. /// <param name="input">输入mat 3通道 bgr格式</param>
  53. /// <param name="resultDic">label confiden 字典</param>
  54. /// <param name="catagory">模型类别和模型配置文件对应</param>
  55. /// <param name="item">模型序号和模型配置文件对应</param>
  56. /// <param name="filename">input mat 原图完整路径</param>
  57. public static void AI_ClassImage(string baseUrl, Mat input, ref Dictionary<string, string> resultDic, int catagory = 1000, int item = 2, string filename = "1.jpg")
  58. {
  59. #if cxx_server
  60. AI_ClassImage_cxx(baseUrl, input, ref resultDic, catagory, item, filename);
  61. #else
  62. AI_ClassImage_cshape(baseUrl, input, ref resultDic, catagory, item, filename);
  63. #endif
  64. }
  65. /// <summary>
  66. /// 从分割模型获取二值图 cshape httpserver
  67. /// </summary>
  68. /// <param name="baseUrl">包括ip地址端口号</param>
  69. /// <param name="input">输入mat 3通道 bgr格式</param>
  70. /// <param name="output">输出mat 灰度图</param>
  71. /// <param name="catagory">模型类别和模型配置文件对应</param>
  72. /// <param name="item">模型序号和模型配置文件对应</param>
  73. /// <param name="filename">input mat 原图完整路径</param>
  74. public static void AI_SegmentImage_cshape(string baseUrl, Mat input, ref Mat output, int catagory = 1000, int item = 1, string filename = "1.jpg")
  75. {
  76. string reqUrl = baseUrl + "/api/MetalAI/SegmentImage?catagory=" + catagory.ToString() + "&item=" + item.ToString();
  77. try
  78. {
  79. HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });
  80. var postContent = new MultipartFormDataContent();
  81. string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x"));
  82. postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}");
  83. MemoryStream ms = input.ToMemoryStream(".jpg");
  84. postContent.Add(new StreamContent(ms, (int)ms.Length), "formFiles", Path.GetFileName(filename));
  85. var response = client.PostAsync(reqUrl, postContent).Result;
  86. Console.WriteLine(response);
  87. if (response.IsSuccessStatusCode)
  88. {
  89. var streamFromService = response.Content.ReadAsStreamAsync().Result;
  90. Bitmap bmp = new Bitmap(streamFromService);
  91. output = BitmapConverter.ToMat(bmp);
  92. if (output.Channels() == 4)
  93. {
  94. Cv2.CvtColor(output, output, ColorConversionCodes.BGRA2GRAY);
  95. }
  96. return;
  97. }
  98. }
  99. catch (Exception ex)
  100. {
  101. Console.WriteLine(ex.ToString());
  102. }
  103. }
  104. /// <summary>
  105. /// 从模型获得分类结果 需做进一步筛选获得分类 cshape httpserver
  106. /// </summary>
  107. /// <param name="baseUrl"></param>
  108. /// <param name="input">输入mat 3通道 bgr格式</param>
  109. /// <param name="resultDic">label confiden 字典</param>
  110. /// <param name="catagory">模型类别和模型配置文件对应</param>
  111. /// <param name="item">模型序号和模型配置文件对应</param>
  112. /// <param name="filename">input mat 原图完整路径</param>
  113. public static void AI_ClassImage_cshape(string baseUrl, Mat input, ref Dictionary<string, string> resultDic, int catagory = 1000, int item = 2, string filename = "1.jpg")
  114. {
  115. string reqUrl = baseUrl + "/api/MetalAI/Classify?catagory=" + catagory.ToString() + "&item=" + item.ToString();
  116. try
  117. {
  118. HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });
  119. var postContent = new MultipartFormDataContent();
  120. string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x"));
  121. postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}");
  122. MemoryStream ms = input.ToMemoryStream(".jpg");
  123. postContent.Add(new StreamContent(ms, (int)ms.Length), "formFiles", Path.GetFileName(filename));
  124. var response = client.PostAsync(reqUrl, postContent).Result;
  125. //Console.WriteLine(response);
  126. if (response.IsSuccessStatusCode)
  127. {
  128. var streamFromService = response.Content.ReadAsStringAsync().Result;
  129. resultDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(streamFromService);
  130. //var maxItem = resultDic.OrderByDescending(kvp => double.Parse(kvp.Value)).FirstOrDefault();//获取得分最大元素的方法
  131. return;
  132. }
  133. }
  134. catch (Exception ex)
  135. {
  136. // throw new Exception("保存file异常");
  137. Console.WriteLine(ex.ToString());
  138. }
  139. }
  140. public static bool AI_Test(string baseUrl)
  141. {
  142. bool connect=false;
  143. string reqUrl = baseUrl + "/api/metalai/Test";
  144. try
  145. {
  146. HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });
  147. client.Timeout= TimeSpan.FromSeconds(3);
  148. var response = client.GetAsync(reqUrl).Result;
  149. //Console.WriteLine(response);
  150. if (response.IsSuccessStatusCode)
  151. {
  152. connect=true;
  153. }
  154. }
  155. catch (Exception ex)
  156. {
  157. // throw new Exception("保存file异常");
  158. Console.WriteLine(ex.ToString());
  159. return false;
  160. }
  161. return connect;
  162. }
  163. /// <summary>
  164. /// c++ 服务器 分类模型
  165. /// </summary>
  166. /// <param name="baseUrl"></param>
  167. /// <param name="input"></param>
  168. /// <param name="resultDic"></param>
  169. /// <param name="catagory"></param>
  170. /// <param name="item"></param>
  171. /// <param name="filename"></param>
  172. public static void AI_ClassImage_cxx(string baseUrl, Mat input, ref Dictionary<string, string> resultDic, int catagory = 1000, int item = 2, string filename = "1.jpg")
  173. {
  174. baseUrl = baseUrl + "/api/MetalAI/Classify";
  175. if (input.Empty())
  176. {
  177. return;
  178. }
  179. class_result result = new class_result();
  180. Dictionary<string, float> resluts = new Dictionary<string, float>();
  181. using (var client = new HttpClient())
  182. {
  183. // Create the query parameters
  184. var query = $"?category={catagory}&item={item}";
  185. // Read the image into a byte array
  186. byte[] imageBytes;
  187. Cv2.ImEncode(".png", input, out imageBytes);
  188. // Create the content with image data
  189. var imageContent = new ByteArrayContent(imageBytes);
  190. //imageContent.Headers.ContentLength= imageBytes1.Length;
  191. Console.WriteLine(imageBytes.Length);
  192. // Send the POST request with query parameters
  193. var fullUrl = baseUrl + query;
  194. try
  195. {
  196. }
  197. catch (Exception)
  198. {
  199. throw;
  200. }
  201. var response = client.PostAsync(fullUrl, imageContent).Result;
  202. if (response.IsSuccessStatusCode)
  203. {
  204. var responseData = response.Content.ReadAsStringAsync().Result;
  205. // var result1 = JsonConvert.DeserializeObject<class_result>(responseData);
  206. resluts = JsonConvert.DeserializeObject<Dictionary<string, float>>(responseData);
  207. foreach (var reslt in resluts)
  208. {
  209. resultDic.Add(reslt.Key, reslt.Value.ToString());
  210. }
  211. }
  212. else
  213. {
  214. Console.WriteLine($"HTTP request failed with status code {response.StatusCode}");
  215. }
  216. }
  217. }
  218. /// <summary>
  219. /// c++服务器 unet
  220. /// </summary>
  221. /// <param name="baseUrl"></param>
  222. /// <param name="input"></param>
  223. /// <param name="output"></param>
  224. /// <param name="catagory"></param>
  225. /// <param name="item"></param>
  226. /// <param name="filename"></param>
  227. public static void AI_SegmentImage_cxx(string baseUrl, Mat input, ref Mat output, int catagory = 1000, int item = 1, string filename = "1.jpg")
  228. {
  229. baseUrl = baseUrl + "/api/MetalAI/SegmentImage";
  230. if (input.Empty())
  231. {
  232. return;
  233. }
  234. // Create the query parameters
  235. var query = $"?category={catagory}&item={item}";
  236. var fullUrl = baseUrl + query;
  237. send_image(fullUrl, input, ref output);
  238. }
  239. public static void UploadFile(string url, string filePath)
  240. {
  241. using (var client = new HttpClient())
  242. using (var content = new MultipartFormDataContent())
  243. {
  244. var fileContent = new StreamContent(new FileStream(filePath, FileMode.Open, FileAccess.Read));
  245. fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg"); // 设置正确的MIME类型
  246. content.Add(fileContent, "file", Path.GetFileName(filePath)); // "file"是服务器期望的表单字段名
  247. var response = client.PostAsync(url, content).Result; // 使用.Result等待异步操作完成,这将阻塞当前线程
  248. if (response.IsSuccessStatusCode)
  249. {
  250. Console.WriteLine("File uploaded successfully.");
  251. }
  252. else
  253. {
  254. Console.WriteLine("Error uploading file: " + response.StatusCode);
  255. }
  256. }
  257. }
  258. public static void send_image(string fullUrl, Mat input, ref Mat output)
  259. {
  260. using (var client = new HttpClient())
  261. {
  262. // Create the query parameters
  263. // Read the image into a byte array
  264. byte[] imageBytes;
  265. Cv2.ImEncode(".png", input, out imageBytes);
  266. // Create the content with image data
  267. var imageContent = new ByteArrayContent(imageBytes);
  268. Console.WriteLine(imageBytes.Length);
  269. // Send the POST request with query parameters
  270. var response = client.PostAsync(fullUrl, imageContent).Result;
  271. if (response.IsSuccessStatusCode)
  272. {
  273. //var responseData = response.Content.ReadAsStringAsync().Result;
  274. var streamFromService = response.Content.ReadAsByteArrayAsync().Result;
  275. try
  276. {
  277. output = Cv2.ImDecode(streamFromService, ImreadModes.Grayscale);
  278. }
  279. catch (Exception)
  280. {
  281. throw;
  282. }
  283. }
  284. else
  285. {
  286. Console.WriteLine($"HTTP request failed with status code {response.StatusCode} ");
  287. }
  288. }
  289. }
  290. public static void AI_SegformerImage_cxx(string baseUrl, Mat input, ref Mat output, int catagory = 1000, int item = 1)
  291. {
  292. baseUrl = baseUrl + "/api/MetalAI/SegformerImage";
  293. if (input.Empty())
  294. {
  295. return;
  296. }
  297. var query = $"?category={catagory}&item={item}";
  298. var fullUrl = baseUrl + query;
  299. send_image(fullUrl, input, ref output);
  300. }
  301. }
  302. }