using OpenCvSharp; using OpenCvSharp.Extensions; using System.Net.Http; using System.IO; using System; using System.Collections.Generic; using System.Drawing; using OTSAlgrithm.Serialization; namespace OTSAlgrithm.AI { public class AIHttpClient { protected static NLog.Logger log ; /// /// 从分割模型获取二值图 /// /// /// 输入mat 3通道 bgr格式 /// 输出mat 灰度图 /// 模型类别和模型配置文件对应 /// 模型序号和模型配置文件对应 /// input mat 原图完整路径 public static void SegmentImage(string baseUrl, Mat input, ref Mat output, string catagory, string item, string filename = "1.jpg") { string reqUrl = baseUrl + "/api/MetalAI/SegmentImage?catagory=" + catagory + "&item=" + item; try { HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false }); var postContent = new MultipartFormDataContent(); string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x")); postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}"); MemoryStream ms = input.ToMemoryStream(".jpg"); postContent.Add(new StreamContent(ms, (int)ms.Length), "formFiles", Path.GetFileName(filename)); var response = client.PostAsync(reqUrl, postContent).Result; Console.WriteLine(response); if (response.IsSuccessStatusCode) { var streamFromService = response.Content.ReadAsStreamAsync().Result; Bitmap bmp = new Bitmap(streamFromService); output = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp); if (output.Channels() == 4) { Cv2.CvtColor(output, output, ColorConversionCodes.BGRA2GRAY); } else if (output.Channels() == 3) { Cv2.CvtColor(output, output, ColorConversionCodes.BGR2GRAY); } //if (item >= 8) //{ // Mat gray = new Mat(); // Cv2.CvtColor(output, gray, ColorConversionCodes.BGR2GRAY); // //Mat thin = new Mat(); // //CvXImgProc.Thinning(gray, gray, ThinningTypes.ZHANGSUEN); // //Cv2.BitwiseNot(gray, gray); // //gray = PostProcessor.Run(gray); // //gray = WaterSegmentation.WatershedSegment(gray); // //Cv2.BitwiseNot(gray, gray); // //Cv2.Dilate(gray, gray, Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(3, 3))); // Cv2.CvtColor(gray, output, ColorConversionCodes.GRAY2BGR); //} //else if (item >= 5 && item <= 7) //{ // Cv2.BitwiseNot(output, output); //} return; } } catch (Exception ex) { //LogHelper.Error(ex); Console.WriteLine(ex.ToString()); } } /// /// 从模型获得分类结果 需做进一步筛选获得分类 /// /// /// 输入mat 3通道 bgr格式 /// label confiden 字典 /// 模型类别和模型配置文件对应 /// 模型序号和模型配置文件对应 /// input mat 原图完整路径 public static void AI_ClassImage(string baseUrl, Mat input, ref Dictionary resultDic, int catagory = 1000, int item = 2, string filename = "1.jpg") { string reqUrl = baseUrl + "/api/MetalAI/Classify?catagory=" + catagory.ToString() + "&item=" + item.ToString(); try { HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false }); var postContent = new MultipartFormDataContent(); string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x")); postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}"); MemoryStream ms = input.ToMemoryStream(".jpg"); postContent.Add(new StreamContent(ms, (int)ms.Length), "formFiles", Path.GetFileName(filename)); var response = client.PostAsync(reqUrl, postContent).Result; //Console.WriteLine(response); if (response.IsSuccessStatusCode) { var streamFromService = response.Content.ReadAsStringAsync().Result; //resultDic = JsonConvert.DeserializeObject>(streamFromService); //var maxItem = resultDic.OrderByDescending(kvp => double.Parse(kvp.Value)).FirstOrDefault();//获取得分最大元素的方法 return; } } catch (Exception ex) { // throw new Exception("保存file异常"); Console.WriteLine(ex.ToString()); } } public static bool AI_Test(string baseUrl) { bool connect = false; string reqUrl = baseUrl + "/api/metalai/Test"; try { HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false }); client.Timeout = TimeSpan.FromSeconds(3); var response = client.GetAsync(reqUrl).Result; //Console.WriteLine(response); if (response.IsSuccessStatusCode) { connect = true; } } catch (Exception ex) { // throw new Exception("保存file异常"); Console.WriteLine(ex.ToString()); return false; } return connect; } /// /// 20250611锡球增加 WQ /// /// /// /// /// /// /// public static void SegmentImage(string baseUrl, Mat input, ref Mat output, int catagory = 1000, int item = 1, string filename = "1.jpg") { string reqUrl = baseUrl + "/api/MetalAI/SegmentImage?catagory=" + catagory.ToString() + "&item=" + item.ToString(); try { HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false }); var postContent = new MultipartFormDataContent(); string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x")); postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}"); MemoryStream ms = input.ToMemoryStream(".jpg"); postContent.Add(new StreamContent(ms, (int)ms.Length), "formFiles", Path.GetFileName(filename)); var response = client.PostAsync(reqUrl, postContent).Result; Console.WriteLine(response); if (response.IsSuccessStatusCode) { var streamFromService = response.Content.ReadAsStreamAsync().Result; Bitmap bmp = new Bitmap(streamFromService); output = BitmapConverter.ToMat(bmp); if (output.Channels() == 4) { Cv2.CvtColor(output, output, ColorConversionCodes.BGRA2BGR); } else if (output.Channels() == 1) { Cv2.CvtColor(output, output, ColorConversionCodes.GRAY2BGR); } //if(item >= 4) //{ // Mat gray = new Mat(); // Cv2.CvtColor(output, gray, ColorConversionCodes.BGR2GRAY); // //Mat thin = new Mat(); // //CvXImgProc.Thinning(gray, gray, ThinningTypes.ZHANGSUEN); // //Cv2.BitwiseNot(gray, gray); // gray = PostProcessor.Run(gray); // //gray = WaterSegmentation.WatershedSegment(gray); // //Cv2.BitwiseNot(gray, gray); // //Cv2.Dilate(gray, gray, Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(3, 3))); // Cv2.CvtColor(gray, output, ColorConversionCodes.GRAY2BGR); //} //else if ((item >= 5) && (item <= 7)) //{ // Cv2.BitwiseNot(output, output); //} return; } } catch (Exception ex) { //LogHelper.Error(ex); Console.WriteLine(ex.ToString()); } } /// /// 20250611锡球增加 WQ /// /// /// /// /// /// /// public static AIAnalysisResult DetectObject(string baseUrl, Mat input, string catagory, string item, string filename = "1.jpg") { string reqUrl = baseUrl + "/api/ObjectDetector?catagory=" + catagory.ToString() + "&item=" + item.ToString(); try { HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false }); var postContent = new MultipartFormDataContent(); string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x")); postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}"); MemoryStream ms = input.ToMemoryStream(".jpg"); postContent.Add(new StreamContent(ms, (int)ms.Length), "formFiles", Path.GetFileName(filename)); var response = client.PostAsync(reqUrl, postContent).Result; Console.WriteLine(response); if (response.IsSuccessStatusCode) { var streamFromService = response.Content.ReadAsStringAsync().Result; var obj = JsonHelper.Deserialize(streamFromService); return obj; } } catch (Exception ex) { //LogHelper.Error(ex); Console.WriteLine(ex.ToString()); } return new AIAnalysisResult(); } /// /// 20250611锡球增加 WQ /// /// /// /// /// /// /// public static AIAnalysisResult SegmentImageJson(string baseUrl, Mat input, string category = "1000", string item = "1", string filename = "1.jpg") { log = NLog.LogManager.GetCurrentClassLogger(); string reqUrl = baseUrl + "/api/MetalAI/SegmentImageJson?catagory=" + category + "&item=" + item; try { HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false }); var postContent = new MultipartFormDataContent(); string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x")); postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}"); MemoryStream ms = input.ToMemoryStream(".jpg"); postContent.Add(new StreamContent(ms, (int)ms.Length), "formFiles", Path.GetFileName(filename)); var response = client.PostAsync(reqUrl, postContent).Result; Console.WriteLine(response); if (response.IsSuccessStatusCode) { var streamFromService = response.Content.ReadAsStringAsync().Result; var obj = JsonHelper.Deserialize(streamFromService); return obj; } } catch (Exception ex) { log.Error(ex.ToString()); } return new AIAnalysisResult(); } public static AIAnalysisResult SegmentImageGranule(string baseUrl, Mat input, string category = "1000", string item = "1", float diameter = 0.0f, string filename = "1.jpg") { string reqUrl = baseUrl + "/api/MetalAI/SegmentImageGranule?catagory=" + category + "&item=" + item + "&diameter=" + diameter.ToString(); try { HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false }); var postContent = new MultipartFormDataContent(); string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x")); postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}"); MemoryStream ms = input.ToMemoryStream(".jpg"); postContent.Add(new StreamContent(ms, (int)ms.Length), "formFiles", Path.GetFileName(filename)); var response = client.PostAsync(reqUrl, postContent).Result; Console.WriteLine(response); if (response.IsSuccessStatusCode) { var streamFromService = response.Content.ReadAsStringAsync().Result; var obj = JsonHelper.Deserialize(streamFromService); return obj; } } catch (Exception ex) { //LogHelper.Error(ex); Console.WriteLine(ex.ToString()); } return new AIAnalysisResult(); } } }