当前位置:   article > 正文

yolov5实例分割跑通以及C#读取yolov5_Seg实例分割转换onnx进行检测部署_segformer转onnx

segformer转onnx

一、首先需要训练yolov5_seg的模型,可以去网上学习,或者你直接用我的,

训练环境和yolov5—7.0的环境一样,你可以直接拷过来用。

yolov5_seg算法

链接:https://pan.baidu.com/s/1m-3lFWRHwg5t8MmIOKm4FA 
提取码:6qiz

或者你直接下载我的环境,都喂你嘴里,就看你吃不吃了,

yolov5_seg算法的环境

链接:https://pan.baidu.com/s/1mwl2poblQUuFEwSpE2dvqA 
提取码:age7

标注就用pip安装labelme就行

标注后是json文件,需要转化成txt

  1. import os
  2. import cv2
  3. import json
  4. import numpy as np
  5. def txt_write(x, img_x, img_y, txt):
  6. data = x['points']
  7. n = 1
  8. for x in data:
  9. for i in x:
  10. if n % 2 == 0:
  11. txt.write(' ' + str(round(i / img_x, 6)))
  12. n += 1
  13. else:
  14. txt.write(' ' + str(round(i / img_y, 6)))
  15. n += 1
  16. txt.write('\n')
  17. def json2txt(json_path, save_path):
  18. txt = open(save_path, 'w')
  19. with open(json_path, "r") as f:
  20. data = f.read()
  21. data = json.loads(data)
  22. img_x = data['imageHeight']
  23. img_y = data['imageWidth']
  24. shapes = data['shapes']
  25. for x in shapes:
  26. # print(x['label'])
  27. # 此处面向不同分类,需要改动下面的标签值,如果是多分类,那么需要增加新的if
  28. # 只是单分类的话,可以直接去掉if,把里面的模块拿出来用
  29. if x['label'] == 'FG':
  30. txt.write('0')
  31. txt_write(x, img_x, img_y, txt)
  32. if x['label'] == 'KP':
  33. txt.write('1')
  34. txt_write(x, img_x, img_y, txt)
  35. #
  36. # if x['label'] == 'ssdp':
  37. # txt.write('2')
  38. # txt_write(x, img_x, img_y, txt)
  39. txt.close()
  40. # 单文件测试
  41. # save_dir = "/workspace/" #文件路径
  42. # name = 'test'
  43. # save_path = save_dir + name + '.txt' # 也可以是.doc
  44. # json_path = '/json/65161.json'
  45. # json2txt(json_path,save_path)
  46. # 文件夹
  47. json_dir = r'H:\DL\yolov5-seg-master\masketcp\PCB_dataset\labels\train'
  48. save_dir = r'H:\DL\yolov5-seg-master\masketcp\PCB_dataset\labels\train'
  49. files = os.listdir(json_dir)
  50. os.makedirs(save_dir, exist_ok=True)
  51. num = 1
  52. for file in files:
  53. name = file[0:-5]
  54. json_path = json_dir + '/' + name + '.json'
  55. save_path = save_dir + '/' + name + '.txt'
  56. json2txt(json_path, save_path)
  57. print(num, '/', len(files), ':', name)
  58. num += 1

然后训练完成后

转化onnx 用export.py 转化就行

二、部署

下载源码 这是一个大佬的代码里面什么都有

https://github.com/guojin-yan/YoloDeployCsharp.git

打开vs2022

安装 OpenCvSharp4 相关的包

openvino 相关的包

剩下的少什么就下载什么就行了

你可能会报错 这个错是因为你的框架是net4.6.1左右的   但是框架换到net6.0就不会错

修改的方法就是

将这里的

\bin\Debug\dll\win-x64

所有dll库复制到带有.exe的文件夹中

也就是  \bin\Debug  中 就可以了

更改参数:

打开

Score_Threshold 置信度也就是小于此值的都被滤掉

NMS_Threshold 非极大值抑制的值,确定框的数量

classes_count_1  类别的个数  你有多少类别你就设置几个

W_H_size_1宽高设定

class_names 是你的类别名

然后我们右键dll程序,生成dll库

将YoloSegDll_all\src\YoloV5_Seg_dll\obj\Debug\YoloV5_Seg_dll.dll路径下的dll文件

引用到控件程序中

主程序代码如下

  1. using Microsoft.ML.OnnxRuntime;
  2. using OpenCvSharp;
  3. using OpenVinoSharp.Extensions.result;
  4. using OpenVinoSharp.Extensions.process;
  5. using SharpCompress.Common;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.ComponentModel;
  9. using System.Data;
  10. using System.Diagnostics;
  11. using System.Drawing;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Text;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using System.Timers;
  18. using System.Windows.Forms;
  19. using YoloDeployPlatform;
  20. using YoloDeployPlatform.predictor;
  21. using Timer = System.Windows.Forms.Timer;
  22. using OpenVinoSharp;
  23. using System.Security.Cryptography;
  24. using YoloDeployPlatform.Properties;
  25. namespace YoloDeployPlatform
  26. {
  27. public partial class YoloDeployPlatform : Form
  28. {
  29. private YOLO yolo = new YOLO();
  30. private Log log = Log.Instance;
  31. private Stopwatch sw = new Stopwatch();
  32. private List<string> class_names= new List<string>();
  33. private VideoCapture video;
  34. private Timer video_timer = new Timer();
  35. private bool timerRunning = false;
  36. private string infer_type = "det";
  37. public YoloDeployPlatform()
  38. {
  39. InitializeComponent();
  40. }
  41. //===============================标签===============已封装为库中===========================
  42. //private void btn_class_select_Click(object sender, EventArgs e)
  43. //{
  44. // //OpenFileDialog dlg = new OpenFileDialog();
  45. // classesLabel label = new classesLabel();
  46. // List<string> classes_name = label.class_names;
  47. //}
  48. //########################## 输入图片 ##########################
  49. //private void btn_input_select_Click(object sender, EventArgs e)
  50. //{
  51. // OpenFileDialog dlg = new OpenFileDialog();
  52. // if (dlg.ShowDialog() == DialogResult.OK)
  53. // {
  54. // string filePath = "";
  55. // filePath=dlg.FileName;
  56. // }
  57. //}
  58. #region RadioButton_CheckedChanged
  59. private void rb_openvino_CheckedChanged(object sender, EventArgs e)
  60. {
  61. if (rb_openvino.Checked)
  62. {
  63. cb_device.Items.Clear();
  64. cb_device.Items.AddRange(new object[] { "AUTO", "CPU", "GPU.0", "GPU.1" });
  65. cb_device.SelectedIndex = 1;
  66. }
  67. }
  68. private void rb_opencv_CheckedChanged(object sender, EventArgs e)
  69. {
  70. if (rb_opencv.Checked)
  71. {
  72. cb_device.Items.Clear();
  73. cb_device.Items.AddRange(new object[] { "CPU"});
  74. cb_device.SelectedIndex = 0;
  75. }
  76. }
  77. #endregion
  78. //############################## 模型读取 & 模型推理 #########################################
  79. private void btn_load_model_Click(object sender, EventArgs e)
  80. {
  81. //读取图片
  82. OpenFileDialog dlg = new OpenFileDialog();
  83. string filePath = "";
  84. if (dlg.ShowDialog() == DialogResult.OK)
  85. {
  86. //tb_input_path.Text = dlg.FileName;
  87. filePath = dlg.FileName;
  88. }
  89. //YOLOv5Seg gb_model = new YOLOv5Seg;
  90. string model_type_str = check_rb(gb_model.Controls);
  91. if (model_type_str == "")
  92. {
  93. show_worn_msg_box("Please select a model category.");
  94. return;
  95. }
  96. string engine_type_str = check_rb(gb_engine.Controls);
  97. if (engine_type_str == "")
  98. {
  99. show_worn_msg_box("Please select an inference engine.");
  100. return;
  101. }
  102. ModelType model_type = MyEnum.GetModelType<ModelType>(model_type_str);
  103. EngineType engine_type = MyEnum.GetEngineType<EngineType>(engine_type_str);
  104. if ((model_type == ModelType.YOLOv5Seg))
  105. {
  106. infer_type = "seg";
  107. }
  108. //================================ model read =======================================
  109. //string model_path = tb_model_path.Text;
  110. string model_path = "F:\\Desk\\models\\bestsegMd.onnx";
  111. string device = cb_device.SelectedItem.ToString();
  112. string extension = Path.GetExtension(model_path);
  113. yolo.Dispose();
  114. //####################################### 阈 值 #################################//
  115. classesLabel my = new classesLabel();
  116. float score = my.Score_Threshold;
  117. float nms = my.NMS_Threshold;
  118. //int categ_num = my.classes_count_1;
  119. int categ_num = 1;
  120. int input_size = my.W_H_size_1;
  121. yolo = YOLO.GetYolo(model_type, model_path, engine_type, device, categ_num, score, nms, input_size);
  122. //############################# 图片处理阶段 ################################################
  123. DateTime start = DateTime.Now;
  124. //string input_path = filePath;
  125. Mat img = Cv2.ImRead(filePath);
  126. sw.Restart();
  127. pictureBox1.BackgroundImage = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(img);
  128. Mat re_img = image_predict(img);
  129. sw.Stop();
  130. pictureBox2.BackgroundImage = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(re_img);
  131. //DateTime end = DateTime.Now;
  132. //label1.Text = "耗时:" + (end - start).TotalMilliseconds.ToString();
  133. label2.Text = sw.ElapsedMilliseconds.ToString();
  134. }
  135. #region
  136. private string check_rb(Control.ControlCollection controls)
  137. {
  138. string key = "";
  139. foreach (Control ctr in controls)
  140. {
  141. if (ctr is RadioButton && (ctr as RadioButton).Checked)
  142. {
  143. key = ctr.Text;
  144. }
  145. }
  146. return key;
  147. }
  148. private void show_worn_msg_box(string message)
  149. {
  150. string caption = "Warning";
  151. MessageBoxButtons buttons = MessageBoxButtons.OK; // 设置按钮
  152. MessageBoxIcon icon = MessageBoxIcon.Warning; // 设置图标
  153. DialogResult result = MessageBox.Show(this, message, caption, buttons, icon);
  154. // 根据用户的点击按钮处理逻辑
  155. if (result == DialogResult.OK)
  156. {
  157. // 用户点击了OK
  158. return;
  159. }
  160. }
  161. Mat image_predict(Mat img, bool is_video = false)
  162. {
  163. Mat re_img = new Mat();
  164. BaseResult result;
  165. if (log.flag_time && !is_video)
  166. {
  167. log.flag_time = false;
  168. yolo.predict(img);
  169. log.flag_time = true;
  170. result = yolo.predict(img);
  171. }
  172. else
  173. {
  174. result = yolo.predict(img);
  175. }
  176. if (class_names.Count > 0)
  177. {
  178. result.update_lable(class_names);
  179. }
  180. re_img = Visualize.draw_seg_result(result, img);
  181. //}
  182. if (log.flag_time && log.flag_fps)
  183. {
  184. Cv2.Rectangle(re_img, new OpenCvSharp.Point(30, 20), new OpenCvSharp.Point(250, 60),
  185. new Scalar(0.0, 255.0, 255.0), -1);
  186. Cv2.PutText(re_img, "FPS: " + (1000.0 / log.infer_time).ToString("0.00"), new OpenCvSharp.Point(50, 50),
  187. HersheyFonts.HersheySimplex, 0.8, new Scalar(0, 0, 0), 2);
  188. }
  189. return re_img;
  190. }
  191. #endregion
  192. private void btn_time_Click(object sender, EventArgs e)
  193. {
  194. log.print();
  195. }
  196. }
  197. }

效果演示

有问题可以加我 qq 2045618826 

当然你可以直接在大佬的代码上面修改

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/803622
推荐阅读
相关标签
  

闽ICP备14008679号