当前位置:   article > 正文

C# danbooru Stable Diffusion 提示词反推 Onnx Demo

C# danbooru Stable Diffusion 提示词反推 Onnx Demo

目录

说明

效果

模型信息

项目

代码

下载 


C# danbooru Stable Diffusion 提示词反推 Onnx Demo

说明

模型下载地址:https://huggingface.co/deepghs/ml-danbooru-onnx

效果

模型信息

Model Properties
-------------------------
---------------------------------------------------------------

Inputs
-------------------------
name:input
tensor:Float[-1, 3, -1, -1]
---------------------------------------------------------------

Outputs
-------------------------
name:output
tensor:Float[-1, 12547]
--------------------------------------------------------------- 

项目

代码

  1. using Microsoft.ML.OnnxRuntime;
  2. using Microsoft.ML.OnnxRuntime.Tensors;
  3. using OpenCvSharp;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Drawing;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Windows.Forms;
  11. namespace Onnx_Demo
  12. {
  13. public partial class Form1 : Form
  14. {
  15. public Form1()
  16. {
  17. InitializeComponent();
  18. }
  19. string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
  20. string image_path = "";
  21. DateTime dt1 = DateTime.Now;
  22. DateTime dt2 = DateTime.Now;
  23. string model_path;
  24. Mat image;
  25. SessionOptions options;
  26. InferenceSession onnx_session;
  27. Tensor<float> input_tensor;
  28. List<NamedOnnxValue> input_container;
  29. IDisposableReadOnlyCollection<DisposableNamedOnnxValue> result_infer;
  30. DisposableNamedOnnxValue[] results_onnxvalue;
  31. Tensor<float> result_tensors;
  32. StringBuilder sb = new StringBuilder();
  33. public string[] class_names;
  34. private void button1_Click(object sender, EventArgs e)
  35. {
  36. OpenFileDialog ofd = new OpenFileDialog();
  37. ofd.Filter = fileFilter;
  38. if (ofd.ShowDialog() != DialogResult.OK) return;
  39. pictureBox1.Image = null;
  40. image_path = ofd.FileName;
  41. pictureBox1.Image = new Bitmap(image_path);
  42. textBox1.Text = "";
  43. image = new Mat(image_path);
  44. }
  45. private void button2_Click(object sender, EventArgs e)
  46. {
  47. if (image_path == "")
  48. {
  49. return;
  50. }
  51. button2.Enabled = false;
  52. textBox1.Text = "";
  53. sb.Clear();
  54. Application.DoEvents();
  55. image = new Mat(image_path);
  56. // 将图片转为RGB通道
  57. Cv2.CvtColor(image, image, ColorConversionCodes.BGR2RGB);
  58. // 输入Tensor
  59. input_tensor = new DenseTensor<float>(new[] { 1, 3, image.Height, image.Width });
  60. // 输入Tensor
  61. for (int y = 0; y < image.Height; y++)
  62. {
  63. for (int x = 0; x < image.Width; x++)
  64. {
  65. input_tensor[0, 0, y, x] = image.At<Vec3b>(y, x)[0] / 255f;
  66. input_tensor[0, 1, y, x] = image.At<Vec3b>(y, x)[1] / 255f;
  67. input_tensor[0, 2, y, x] = image.At<Vec3b>(y, x)[2] / 255f;
  68. }
  69. }
  70. //input_tensor 放入一个输入参数的容器,并指定名称
  71. input_container.Add(NamedOnnxValue.CreateFromTensor("input", input_tensor));
  72. dt1 = DateTime.Now;
  73. //运行 Inference 并获取结果
  74. result_infer = onnx_session.Run(input_container);
  75. dt2 = DateTime.Now;
  76. // 将输出结果转为DisposableNamedOnnxValue数组
  77. results_onnxvalue = result_infer.ToArray();
  78. // 读取第一个节点输出并转为Tensor数据
  79. result_tensors = results_onnxvalue[0].AsTensor<float>();
  80. var result_array = result_tensors.ToArray();
  81. double[] scores = new double[result_array.Length];
  82. for (int i = 0; i < result_array.Length; i++)
  83. {
  84. double score = 1 / (1 + Math.Exp(result_array[i] * -1));
  85. scores[i] = score;
  86. }
  87. List<ScoreIndex> ltResult = new List<ScoreIndex>();
  88. ScoreIndex temp;
  89. for (int i = 0; i < scores.Length; i++)
  90. {
  91. temp = new ScoreIndex(i, scores[i]);
  92. ltResult.Add(temp);
  93. }
  94. //根据分数倒序排序,取前10
  95. var SortedByScore = ltResult.OrderByDescending(p => p.Score).ToList().Take(10);
  96. foreach (var item in SortedByScore)
  97. {
  98. sb.Append(class_names[item.Index] + ",");
  99. }
  100. sb.Length--; // 将长度减1来移除最后一个字符
  101. sb.AppendLine("");
  102. sb.AppendLine("------------------");
  103. // 只取分数最高的
  104. // float max = result_array.Max();
  105. // int maxIndex = Array.IndexOf(result_array, max);
  106. // sb.AppendLine(class_names[maxIndex]+" "+ max.ToString("P2"));
  107. sb.AppendLine("推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms");
  108. textBox1.Text = sb.ToString();
  109. button2.Enabled = true;
  110. }
  111. private void Form1_Load(object sender, EventArgs e)
  112. {
  113. model_path = "model/ml_danbooru.onnx";
  114. // 创建输出会话,用于输出模型读取信息
  115. options = new SessionOptions();
  116. options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_INFO;
  117. options.AppendExecutionProvider_CPU(0);// 设置为CPU上运行
  118. // 创建推理模型类,读取本地模型文件
  119. onnx_session = new InferenceSession(model_path, options);//model_path 为onnx模型文件的路径
  120. // 创建输入容器
  121. input_container = new List<NamedOnnxValue>();
  122. image_path = "test_img/2.jpg";
  123. pictureBox1.Image = new Bitmap(image_path);
  124. image = new Mat(image_path);
  125. List<string> str = new List<string>();
  126. StreamReader sr = new StreamReader("model/lable.txt");
  127. string line;
  128. while ((line = sr.ReadLine()) != null)
  129. {
  130. str.Add(line);
  131. }
  132. class_names = str.ToArray();
  133. }
  134. }
  135. }

下载 

源码下载

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

闽ICP备14008679号