翼度科技»论坛 编程开发 .net 查看内容

【OpenVINO™】基于 C# 和 OpenVINO™ 部署 Blazeface 模型实现人脸检测

5

主题

5

帖子

15

积分

新手上路

Rank: 1

积分
15
 前言OpenVINO™ C# API 是一个 OpenVINO™ 的 .Net wrapper,应用最新的 OpenVINO™ 库开发,通过 OpenVINO™ C API 实现 .Net 对 OpenVINO™ Runtime 调用,使用习惯与 OpenVINO™ C++ API 一致。OpenVINO™ C# API 由于是基于 OpenVINO™ 开发,所支持的平台与 OpenVINO™ 完全一致,具体信息可以参考 OpenVINO™。通过使用 OpenVINO™ C# API,可以在 .NET、.NET Framework等框架下使用 C# 语言实现深度学习模型在指定平台推理加速。
OpenVINO™ C# API 项目链接为:
  1. https://github.com/guojin-yan/OpenVINO-CSharp-API.git
复制代码
项目源码链接为:
  1. https://github.com/guojin-yan/OpenVINO-CSharp-API-Samples.git
复制代码
1. 简介

     Blazeface模型是Google推出的一款专为移动GPU推理量身定制的轻量级且性能卓越的人脸检测器,BlazeFace 在旗舰移动设备上以200-1000 + FPS的速度运行。 在本文中,我们将使用OpenVINO™ C# API 部署 Blazeface 实现人脸检测。
2. 项目环境与依赖

     该项目中所需依赖已经支持通过NuGet Package进行安装,在该项目中,需要安装以下NuGet Package:

  • OpenVINO C# API NuGet Package:
  1. OpenVINO.CSharp.API
  2. OpenVINO.runtime.win
  3. OpenVINO.CSharp.API.Extensions
复制代码

  • OpenCvSharp NuGet Package:
  1. OpenCvSharp4
  2. OpenCvSharp4.Extensions
  3. OpenCvSharp4.runtime.win
复制代码
3. 项目输出

     项目使用的是控制台输出,运行后输出如下所示:
  1. <00:00:00> Sending http request to https://github.com/guojin-yan/OpenVINO-CSharp-API-Samples/releases/download/Model/blazeface_1000e.tar.
  2. <00:00:01> Http Response Accquired.
  3. <00:00:01> Total download length is 0.47 Mb.
  4. <00:00:01> Download Started.
  5. <00:00:01> File created.
  6. <00:00:01> Downloading: [■■■■■■■■■■] 100% <00:00:01 0.24 Mb/s> 0.47 Mb/0.47 Mb downloaded.
  7. <00:00:01> File Downloaded, saved in E:\GitSpace\OpenVINO-CSharp-API-Samples\model_samples\face_detection\blazeface_opencvsharp\bin\Release\net6.0\model\blazeface_1000e.tar.
  8. <00:00:00> Sending http request to https://github.com/guojin-yan/OpenVINO-CSharp-API-Samples/releases/download/Image/face1.jpg.
  9. <00:00:01> Http Response Accquired.
  10. <00:00:01> Total download length is 0.14 Mb.
  11. <00:00:01> Download Started.
  12. <00:00:01> File created.
  13. <00:00:01> Downloading: [■■■■■■■■■■] 100% <00:00:01 0.08 Mb/s> 0.14 Mb/0.14 Mb downloaded.
  14. <00:00:01> File Downloaded, saved in E:\GitSpace\OpenVINO-CSharp-API-Samples\model_samples\face_detection\blazeface_opencvsharp\bin\Release\net6.0\model\face1.jpg.
  15. [ INFO ] ---- OpenVINO INFO----
  16. [ INFO ] Description : OpenVINO Runtime
  17. [ INFO ] Build number: 2024.0.0-14509-34caeefd078-releases/2024/0
  18. [ INFO ] Predict model files: ./model/blazeface_1000e.xml
  19. [ INFO ] Predict image  files: ./model/face1.jpg
  20. [ INFO ] Inference device: CPU
  21. [ INFO ] Start RT-DETR model inference.
  22. [ INFO ] 1. Initialize OpenVINO Runtime Core success, time spend: 3.2045ms.
  23. [ INFO ] 2. Read inference model success, time spend: 46.1753ms.
  24. [ INFO ] Inference Model
  25. [ INFO ]   Model name: Model0
  26. [ INFO ]   Input:
  27. [ INFO ]      name: scale_factor
  28. [ INFO ]      type: float
  29. [ INFO ]      shape: Shape : {1,2}
  30. [ INFO ]      name: image
  31. [ INFO ]      type: float
  32. [ INFO ]      shape: Shape : {1,3,640,640}
  33. [ INFO ]      name: im_shape
  34. [ INFO ]      type: float
  35. [ INFO ]      shape: Shape : {1,2}
  36. [ INFO ]   Output:
  37. [ INFO ]      name: multiclass_nms3_0.tmp_0
  38. [ INFO ]      type: float
  39. [ INFO ]      shape: Shape : {750,6}
  40. [ INFO ]      name: multiclass_nms3_0.tmp_2
  41. [ INFO ]      type: int32_t
  42. [ INFO ]      shape: Shape : {1}
  43. [ INFO ] 3. Loading a model to the device success, time spend:213.1551ms.
  44. [ INFO ] 4. Create an infer request success, time spend:0.4506ms.
  45. [ INFO ] 5. Process input images success, time spend:74.6076ms.
  46. [ INFO ] 6. Set up input data success, time spend:1.7392ms.
  47. [ INFO ] 7. Do inference synchronously success, time spend:21.3498ms.
  48. [ INFO ] 8. Get infer result data success, time spend:1.1302ms.
  49. [ INFO ] 9. Process reault  success, time spend:0.4035ms.
  50. [ INFO ] The result save to E:\GitSpace\OpenVINO-CSharp-API-Samples\model_samples\face_detection\blazeface_opencvsharp\bin\Release\net6.0\model\face1_result.jpg
复制代码
     图像预测结果如下图所示:

4. 代码展示

     以下为嘛中所使用的命名空间代码:
  1. using OpenCvSharp.Dnn;
  2. using OpenCvSharp;
  3. using OpenVinoSharp;
  4. using OpenVinoSharp.Extensions;
  5. using OpenVinoSharp.Extensions.utility;
  6. using System.Runtime.InteropServices;
  7. using OpenVinoSharp.preprocess;
  8. using OpenVinoSharp.Extensions.result;
  9. using OpenVinoSharp.Extensions.process;
  10. using System;
  11. using System.Reflection.Metadata;
  12. namespace blazeface_opencvsharp
  13. {
  14.     internal class Program
  15.     {   
  16.             ....
  17.     }
  18. }
复制代码
     下面为定义的模型预测代码:
  1. static void face_detection(string model_path, string image_path, string device)
  2. {
  3.     // -------- Step 1. Initialize OpenVINO Runtime Core --------
  4.     Core core = new Core();
  5.     // -------- Step 2. Read inference model --------
  6.     Model model = core.read_model(model_path);
  7.     Dictionary<string, PartialShape> pairs = new Dictionary<string, PartialShape>();
  8.     pairs.Add("scale_factor", new PartialShape(new Shape(1, 2)));
  9.     pairs.Add("im_shape", new PartialShape(new Shape(1, 2)));
  10.     pairs.Add("image", new PartialShape(new Shape(1, 3, 640, 640)));
  11.     model.reshape(pairs);
  12.     OvExtensions.printf_model_info(model);
  13.     // -------- Step 3. Loading a model to the device --------
  14.     CompiledModel compiled_model = core.compile_model(model, device);
  15.     // -------- Step 4. Create an infer request --------
  16.     InferRequest infer_request = compiled_model.create_infer_request();
  17.     // -------- Step 5. Process input images --------
  18.     Mat image = new Mat(image_path); // Read image by opencvsharp
  19.     Mat mat = new Mat();
  20.     Cv2.Resize(image, mat, new Size(640, 640));
  21.     mat = Normalize.run(mat, new float[] { 123f, 117f, 104f }, new float[] { 1 / 127.502231f, 1 / 127.502231f, 1 / 127.502231f },
  22.         false);
  23.     float[] input_data = Permute.run(mat);
  24.     // -------- Step 6. Set up input data --------
  25.     Tensor input_tensor_data = infer_request.get_tensor("image");
  26.     //input_tensor_data.set_shape(new Shape(1, 3, image.Cols, image.Rows));
  27.     input_tensor_data.set_data<float>(input_data);
  28.     Tensor input_tensor_shape = infer_request.get_tensor("im_shape");
  29.     input_tensor_shape.set_shape(new Shape(1, 2));
  30.     input_tensor_shape.set_data<float>(new float[] { 640, 640 });
  31.     Tensor input_tensor_factor = infer_request.get_tensor("scale_factor");
  32.     input_tensor_factor.set_shape(new Shape(1, 2));
  33.     input_tensor_factor.set_data<float>(new float[] { ((float)640.0f / image.Rows), ((float)640.0 / image.Cols) });
  34.     // -------- Step 7. Do inference synchronously --------
  35.     infer_request.infer();
  36.     // -------- Step 8. Get infer result data --------
  37.     Tensor output_tensor = infer_request.get_output_tensor(0);
  38.     Shape output_shape = output_tensor.get_shape();
  39.     int output_length = (int)output_tensor.get_size();
  40.     float[] result_data = output_tensor.get_data<float>(output_length);
  41.     Tensor output_tensor1 = infer_request.get_output_tensor(1);
  42.     int output_length1 = (int)output_tensor1.get_size();
  43.     int[] result_len = output_tensor1.get_data<int>(output_length1);
  44.     // -------- Step 9. Process reault  --------
  45.     List<Rect> position_boxes = new List<Rect>();
  46.     List<float> confidences = new List<float>();
  47.     // Preprocessing output results
  48.     for (int i = 0; i < result_len[0]; i++)
  49.     {
  50.         double confidence = result_data[6 * i + 1];
  51.         if (confidence > 0.5)
  52.         {
  53.             float tlx = result_data[6 * i + 2];
  54.             float tly = result_data[6 * i + 3];
  55.             float brx = result_data[6 * i + 4];
  56.             float bry = result_data[6 * i + 5];
  57.             Rect box = new Rect((int)tlx, (int)tly, (int)(brx - tlx), (int)(bry - tly));
  58.             position_boxes.Add(box);
  59.             confidences.Add((float)confidence);
  60.         }
  61.     }
  62.     for (int i = 0; i < position_boxes.Count; i++)
  63.     {
  64.         int index = i;
  65.         Cv2.Rectangle(image, position_boxes[index], new Scalar(255, 0, 0), 1, LineTypes.Link8);
  66.         Cv2.PutText(image, confidences[index].ToString("0.00"),
  67.             new OpenCvSharp.Point(position_boxes[index].TopLeft.X, position_boxes[index].TopLeft.Y - 5),
  68.             HersheyFonts.HersheySimplex, 0.4, new Scalar(255, 0, 0), 1);
  69.     }
  70.     string output_path = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(image_path)),
  71.         Path.GetFileNameWithoutExtension(image_path) + "_result.jpg");
  72.     Cv2.ImWrite(output_path, image);
  73.     Slog.INFO("The result save to " + output_path);
  74.     Cv2.ImShow("Result", image);
  75.     Cv2.WaitKey(0);
  76. }
复制代码
     下面为程序运行的主函数代码,该代码会下载转换好的预测模型,并调用预测方法进行预测:
  1. static void Main(string[] args)
  2. {
  3.     string model_path = "";
  4.     string image_path = "";
  5.     string device = "CPU";
  6.     if (args.Length == 0)
  7.     {
  8.         if (!Directory.Exists("./model"))
  9.         {
  10.             Directory.CreateDirectory("./model");
  11.         }
  12.         if (!File.Exists("./model/blazeface_1000e.xml")
  13.             && !File.Exists("./model/blazeface_1000e.bin"))
  14.         {
  15.             if (!File.Exists("./model/blazeface_1000e.tar"))
  16.             {
  17.                 _ = Download.download_file_async("https://github.com/guojin-yan/OpenVINO-CSharp-API-Samples/releases/download/Model/blazeface_1000e.tar",
  18.                     "./model/blazeface_1000e.tar").Result;
  19.             }
  20.             Download.unzip("./model/blazeface_1000e.tar", "./model/");
  21.         }
  22.         if (!File.Exists("./model/face1.jpg"))
  23.         {
  24.             _ = Download.download_file_async("https://github.com/guojin-yan/OpenVINO-CSharp-API-Samples/releases/download/Image/face1.jpg",
  25.                 "./model/face1.jpg").Result;
  26.         }
  27.         model_path = "./model/blazeface_1000e.xml";
  28.         image_path = "./model/face1.jpg";
  29.     }
  30.     else if (args.Length >= 2)
  31.     {
  32.         model_path = args[0];
  33.         image_path = args[1];
  34.         device = args[2];
  35.     }
  36.     else
  37.     {
  38.         Console.WriteLine("Please enter the correct command parameters, for example:");
  39.         Console.WriteLine("> 1. dotnet run");
  40.         Console.WriteLine("> 2. dotnet run <model path> <image path> <device name>");
  41.     }
  42.     // -------- Get OpenVINO runtime version --------
  43.     OpenVinoSharp.Version version = Ov.get_openvino_version();
  44.     Slog.INFO("---- OpenVINO INFO----");
  45.     Slog.INFO("Description : " + version.description);
  46.     Slog.INFO("Build number: " + version.buildNumber);
  47.     Slog.INFO("Predict model files: " + model_path);
  48.     Slog.INFO("Predict image  files: " + image_path);
  49.     Slog.INFO("Inference device: " + device);
  50.     Slog.INFO("Start RT-DETR model inference.");
  51.     face_detection(model_path, image_path, device);
  52. }
复制代码
5. 总结

     在该项目中,我们结合之前开发的 OpenVINO™ C# API 项目部署 Blazeface 模型,成功实现了人脸检测。

  • 项目完整代码链接为:
  1. https://github.com/guojin-yan/OpenVINO-CSharp-API-Samples/blob/master/model_samples/face_detection/blazeface_opencvsharp/Program.cs
复制代码

  • 为了方便EmguCV用户使用需求,同时开发了EmguCV版本,项目链接为:
  1. https://github.com/guojin-yan/OpenVINO-CSharp-API-Samples/blob/master/model_samples/face_detection/blazeface_emgucv/Program.cs
复制代码
最后如果各位开发者在使用中有任何问题,欢迎大家与我联系。

来源:https://www.cnblogs.com/guojin-blogs/p/18179021
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具