123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327 |
- #define cxx_server
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Runtime.InteropServices.ComTypes;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using Newtonsoft.Json;
- using OpenCvSharp;
- using System.Drawing;
- using OpenCvSharp.Extensions;
- using Newtonsoft.Json.Linq;
- using System.Runtime.InteropServices;
- using System.Security.Policy;
- using static OpenCvSharp.XImgProc.CvXImgProc;
- namespace OTSModelSharp.ServiceCenter
- {
- public class class_result
- {
- public string Result { get; set; }
- public float Confidence { get; set; }
- }
- public class AI_HttpClient
- {
- /// <summary>
- /// 从分割模型获取二值图
- /// </summary>
- /// <param name="baseUrl">包括ip地址端口号</param>
- /// <param name="input">输入mat 3通道 bgr格式</param>
- /// <param name="output">输出mat 灰度图</param>
- /// <param name="catagory">模型类别和模型配置文件对应</param>
- /// <param name="item">模型序号和模型配置文件对应</param>
- /// <param name="filename">input mat 原图完整路径</param>
- public static void AI_SegmentImage(string baseUrl, Mat input, ref Mat output, int catagory = 1000, int item = 1, string filename = "1.jpg")
- {
- #if cxx_server
- AI_SegmentImage_cxx(baseUrl, input, ref output, catagory, item, filename);
- #else
- AI_SegmentImage_cshape(baseUrl, input, ref output, catagory, item, filename);
- #endif
- }
- /// <summary>
- /// 从模型获得分类结果 需做进一步筛选获得分类
- /// </summary>
- /// <param name="baseUrl"></param>
- /// <param name="input">输入mat 3通道 bgr格式</param>
- /// <param name="resultDic">label confiden 字典</param>
- /// <param name="catagory">模型类别和模型配置文件对应</param>
- /// <param name="item">模型序号和模型配置文件对应</param>
- /// <param name="filename">input mat 原图完整路径</param>
- public static void AI_ClassImage(string baseUrl, Mat input, ref Dictionary<string, string> resultDic, int catagory = 1000, int item = 2, string filename = "1.jpg")
- {
- #if cxx_server
- AI_ClassImage_cxx(baseUrl, input, ref resultDic, catagory, item, filename);
- #else
- AI_ClassImage_cshape(baseUrl, input, ref resultDic, catagory, item, filename);
- #endif
- }
- /// <summary>
- /// 从分割模型获取二值图 cshape httpserver
- /// </summary>
- /// <param name="baseUrl">包括ip地址端口号</param>
- /// <param name="input">输入mat 3通道 bgr格式</param>
- /// <param name="output">输出mat 灰度图</param>
- /// <param name="catagory">模型类别和模型配置文件对应</param>
- /// <param name="item">模型序号和模型配置文件对应</param>
- /// <param name="filename">input mat 原图完整路径</param>
- public static void AI_SegmentImage_cshape(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.BGRA2GRAY);
- }
- return;
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.ToString());
- }
- }
- /// <summary>
- /// 从模型获得分类结果 需做进一步筛选获得分类 cshape httpserver
- /// </summary>
- /// <param name="baseUrl"></param>
- /// <param name="input">输入mat 3通道 bgr格式</param>
- /// <param name="resultDic">label confiden 字典</param>
- /// <param name="catagory">模型类别和模型配置文件对应</param>
- /// <param name="item">模型序号和模型配置文件对应</param>
- /// <param name="filename">input mat 原图完整路径</param>
- 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")
- {
- 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<Dictionary<string, string>>(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;
- }
- /// <summary>
- /// c++ 服务器 分类模型
- /// </summary>
- /// <param name="baseUrl"></param>
- /// <param name="input"></param>
- /// <param name="resultDic"></param>
- /// <param name="catagory"></param>
- /// <param name="item"></param>
- /// <param name="filename"></param>
- 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")
- {
- baseUrl = baseUrl + "/api/MetalAI/Classify";
- if (input.Empty())
- {
- return;
- }
- class_result result = new class_result();
- Dictionary<string, float> resluts = new Dictionary<string, float>();
- using (var client = new HttpClient())
- {
- // Create the query parameters
- var query = $"?category={catagory}&item={item}";
- // Read the image into a byte array
- byte[] imageBytes;
- Cv2.ImEncode(".png", input, out imageBytes);
- // Create the content with image data
- var imageContent = new ByteArrayContent(imageBytes);
- //imageContent.Headers.ContentLength= imageBytes1.Length;
- Console.WriteLine(imageBytes.Length);
- // Send the POST request with query parameters
- var fullUrl = baseUrl + query;
- try
- {
- }
- catch (Exception)
- {
- throw;
- }
- var response = client.PostAsync(fullUrl, imageContent).Result;
- if (response.IsSuccessStatusCode)
- {
- var responseData = response.Content.ReadAsStringAsync().Result;
- // var result1 = JsonConvert.DeserializeObject<class_result>(responseData);
- resluts = JsonConvert.DeserializeObject<Dictionary<string, float>>(responseData);
- foreach (var reslt in resluts)
- {
- resultDic.Add(reslt.Key, reslt.Value.ToString());
- }
- }
- else
- {
- Console.WriteLine($"HTTP request failed with status code {response.StatusCode}");
- }
- }
- }
- /// <summary>
- /// c++服务器 unet
- /// </summary>
- /// <param name="baseUrl"></param>
- /// <param name="input"></param>
- /// <param name="output"></param>
- /// <param name="catagory"></param>
- /// <param name="item"></param>
- /// <param name="filename"></param>
- public static void AI_SegmentImage_cxx(string baseUrl, Mat input, ref Mat output, int catagory = 1000, int item = 1, string filename = "1.jpg")
- {
- baseUrl = baseUrl + "/api/MetalAI/SegmentImage";
- if (input.Empty())
- {
- return;
- }
- // Create the query parameters
- var query = $"?category={catagory}&item={item}";
- var fullUrl = baseUrl + query;
- send_image(fullUrl, input, ref output);
- }
- public static void UploadFile(string url, string filePath)
- {
- using (var client = new HttpClient())
- using (var content = new MultipartFormDataContent())
- {
- var fileContent = new StreamContent(new FileStream(filePath, FileMode.Open, FileAccess.Read));
- fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg"); // 设置正确的MIME类型
- content.Add(fileContent, "file", Path.GetFileName(filePath)); // "file"是服务器期望的表单字段名
- var response = client.PostAsync(url, content).Result; // 使用.Result等待异步操作完成,这将阻塞当前线程
- if (response.IsSuccessStatusCode)
- {
- Console.WriteLine("File uploaded successfully.");
- }
- else
- {
- Console.WriteLine("Error uploading file: " + response.StatusCode);
- }
- }
- }
- public static void send_image(string fullUrl, Mat input, ref Mat output)
- {
- using (var client = new HttpClient())
- {
- // Create the query parameters
- // Read the image into a byte array
- byte[] imageBytes;
- Cv2.ImEncode(".png", input, out imageBytes);
- // Create the content with image data
- var imageContent = new ByteArrayContent(imageBytes);
- Console.WriteLine(imageBytes.Length);
- // Send the POST request with query parameters
- var response = client.PostAsync(fullUrl, imageContent).Result;
- if (response.IsSuccessStatusCode)
- {
- //var responseData = response.Content.ReadAsStringAsync().Result;
- var streamFromService = response.Content.ReadAsByteArrayAsync().Result;
- try
- {
- output = Cv2.ImDecode(streamFromService, ImreadModes.Grayscale);
- }
- catch (Exception)
- {
- throw;
- }
- }
- else
- {
- Console.WriteLine($"HTTP request failed with status code {response.StatusCode} ");
- }
- }
- }
- public static void AI_SegformerImage_cxx(string baseUrl, Mat input, ref Mat output, int catagory = 1000, int item = 1)
- {
- baseUrl = baseUrl + "/api/MetalAI/SegformerImage";
- if (input.Empty())
- {
- return;
- }
- var query = $"?category={catagory}&item={item}";
- var fullUrl = baseUrl + query;
- send_image(fullUrl, input, ref output);
- }
- }
- }
|