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

embedded/2024/9/23 8:45:59/

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

目录

说明

效果

模型信息

项目

代码

下载 


说明

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

效果

模型信息

OVVersion { BuildNumber = 2023.1.0-12185-9e6b00e51cd-releases/2023/1, Description = OpenVINO Runtime }
---------------------------------------------------------------
本机可用设备
CPU
GNA
GPU
---------------------------------------------------------------

Inputs
-------------------------
name:input
tensor:F32[?, 3, ?, ?]

---------------------------------------------------------------

Outputs
-------------------------
name:output
tensor:F32[?, 12547]

---------------------------------------------------------------

项目

代码

using OpenCvSharp;
using Sdcb.OpenVINO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace C__danbooru_Stable_Diffusion_提示词反推_OpenVINO__Demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
        string image_path = "";
        string model_path;
        Mat image;

        StringBuilder sb = new StringBuilder();
        public string[] class_names;

        Model rawModel;
        PrePostProcessor pp;
        Model m;
        CompiledModel cm;
        InferRequest ir;

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = fileFilter;
            if (ofd.ShowDialog() != DialogResult.OK) return;
            pictureBox1.Image = null;
            image_path = ofd.FileName;
            pictureBox1.Image = new Bitmap(image_path);
            textBox1.Text = "";
            image = new Mat(image_path);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (image_path == "")
            {
                return;
            }

            button2.Enabled = false;
            textBox1.Text = "";
            sb.Clear();
            Application.DoEvents();

            image = new Mat(image_path);


            image = new Mat(image_path);
            int w = image.Width;
            int h = image.Height;

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            float[] input_tensor_data;

            image.ConvertTo(image, MatType.CV_32FC3, 1.0 / 255);
            input_tensor_data = Common.ExtractMat(image);

            Tensor input_tensor = Tensor.FromArray(input_tensor_data, new Shape(1, 3, h, w));

            ir.Inputs[0] = input_tensor;

            double preprocessTime = stopwatch.Elapsed.TotalMilliseconds;
            stopwatch.Restart();

            ir.Run();

            double inferTime = stopwatch.Elapsed.TotalMilliseconds;

            stopwatch.Restart();

            var result_array = ir.Outputs[0].GetData<float>().ToArray();

            double[] scores = new double[result_array.Length];
            for (int i = 0; i < result_array.Length; i++)
            {
                double score = 1 / (1 + Math.Exp(result_array[i] * -1));
                scores[i] = score;
            }

            List<ScoreIndex> ltResult = new List<ScoreIndex>();
            ScoreIndex temp;
            for (int i = 0; i < scores.Length; i++)
            {
                temp = new ScoreIndex(i, scores[i]);
                ltResult.Add(temp);
            }

            //根据分数倒序排序,取前10个
            var SortedByScore = ltResult.OrderByDescending(p => p.Score).ToList().Take(10);

            foreach (var item in SortedByScore)
            {
                sb.Append(class_names[item.Index] + ",");
            }
            sb.Length--; // 将长度减1来移除最后一个字符

            sb.AppendLine("");
            sb.AppendLine("------------------");


            double postprocessTime = stopwatch.Elapsed.TotalMilliseconds;
            stopwatch.Stop();

            double totalTime = preprocessTime + inferTime + postprocessTime;

            sb.AppendLine($"Preprocess: {preprocessTime:F2}ms");
            sb.AppendLine($"Infer: {inferTime:F2}ms");
            sb.AppendLine($"Postprocess: {postprocessTime:F2}ms");
            sb.AppendLine($"Total: {totalTime:F2}ms");
            textBox1.Text = sb.ToString();
            button2.Enabled = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            model_path = "model/ml_danbooru.onnx";

            image_path = "test_img/2.jpg";
            pictureBox1.Image = new Bitmap(image_path);
            image = new Mat(image_path);

            List<string> str = new List<string>();
            StreamReader sr = new StreamReader("model/lable.txt");
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                str.Add(line);
            }
            class_names = str.ToArray();


            rawModel = OVCore.Shared.ReadModel(model_path);
            pp = rawModel.CreatePrePostProcessor();

            m = pp.BuildModel();
            cm = OVCore.Shared.CompileModel(m, "CPU");
            ir = cm.CreateInferRequest();

        }
    }
}

using OpenCvSharp;
using Sdcb.OpenVINO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace C__danbooru_Stable_Diffusion_提示词反推_OpenVINO__Demo
{public partial class Form1 : Form{public Form1(){InitializeComponent();}string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";string image_path = "";string model_path;Mat image;StringBuilder sb = new StringBuilder();public string[] class_names;Model rawModel;PrePostProcessor pp;Model m;CompiledModel cm;InferRequest ir;private void button1_Click(object sender, EventArgs e){OpenFileDialog ofd = new OpenFileDialog();ofd.Filter = fileFilter;if (ofd.ShowDialog() != DialogResult.OK) return;pictureBox1.Image = null;image_path = ofd.FileName;pictureBox1.Image = new Bitmap(image_path);textBox1.Text = "";image = new Mat(image_path);}private void button2_Click(object sender, EventArgs e){if (image_path == ""){return;}button2.Enabled = false;textBox1.Text = "";sb.Clear();Application.DoEvents();image = new Mat(image_path);image = new Mat(image_path);int w = image.Width;int h = image.Height;Stopwatch stopwatch = new Stopwatch();stopwatch.Start();float[] input_tensor_data;image.ConvertTo(image, MatType.CV_32FC3, 1.0 / 255);input_tensor_data = Common.ExtractMat(image);Tensor input_tensor = Tensor.FromArray(input_tensor_data, new Shape(1, 3, h, w));ir.Inputs[0] = input_tensor;double preprocessTime = stopwatch.Elapsed.TotalMilliseconds;stopwatch.Restart();ir.Run();double inferTime = stopwatch.Elapsed.TotalMilliseconds;stopwatch.Restart();var result_array = ir.Outputs[0].GetData<float>().ToArray();double[] scores = new double[result_array.Length];for (int i = 0; i < result_array.Length; i++){double score = 1 / (1 + Math.Exp(result_array[i] * -1));scores[i] = score;}List<ScoreIndex> ltResult = new List<ScoreIndex>();ScoreIndex temp;for (int i = 0; i < scores.Length; i++){temp = new ScoreIndex(i, scores[i]);ltResult.Add(temp);}//根据分数倒序排序,取前10个var SortedByScore = ltResult.OrderByDescending(p => p.Score).ToList().Take(10);foreach (var item in SortedByScore){sb.Append(class_names[item.Index] + ",");}sb.Length--; // 将长度减1来移除最后一个字符sb.AppendLine("");sb.AppendLine("------------------");double postprocessTime = stopwatch.Elapsed.TotalMilliseconds;stopwatch.Stop();double totalTime = preprocessTime + inferTime + postprocessTime;sb.AppendLine($"Preprocess: {preprocessTime:F2}ms");sb.AppendLine($"Infer: {inferTime:F2}ms");sb.AppendLine($"Postprocess: {postprocessTime:F2}ms");sb.AppendLine($"Total: {totalTime:F2}ms");textBox1.Text = sb.ToString();button2.Enabled = true;}private void Form1_Load(object sender, EventArgs e){model_path = "model/ml_danbooru.onnx";image_path = "test_img/2.jpg";pictureBox1.Image = new Bitmap(image_path);image = new Mat(image_path);List<string> str = new List<string>();StreamReader sr = new StreamReader("model/lable.txt");string line;while ((line = sr.ReadLine()) != null){str.Add(line);}class_names = str.ToArray();rawModel = OVCore.Shared.ReadModel(model_path);pp = rawModel.CreatePrePostProcessor();m = pp.BuildModel();cm = OVCore.Shared.CompileModel(m, "CPU");ir = cm.CreateInferRequest();}}
}

下载 

源码下载


http://www.ppmy.cn/embedded/13241.html

相关文章

Qt5中的常用模块

2024年4月23日&#xff0c;周二上午 以下是 Qt5 中常用的模块列表&#xff1a; 核心模块&#xff08;Core&#xff09;&#xff1a;提供了 Qt 核心功能&#xff0c;包括对象模型、信号与槽机制、事件处理等。图形模块&#xff08;Gui&#xff09;&#xff1a;提供了绘图和窗口…

JOS工具链平台迁移:从Linux到Windows

写在前面 在写这篇文章的时候&#xff0c;我已经把MIT 6.828的课程实验都做完了&#xff0c;相关的文章也会陆续更新。但是由于写文章把事情讲清楚的难度确实比做实验的难度大很多&#xff0c;所以更新速度可能会比较慢&#xff0c;还请谅解。 后续我决定在这个课程实验的基础…

注册中心~

注册中心&#xff1a;是服务实例信息的存储仓库&#xff0c;也是服务提供者和服务消费者进行交互的桥梁。它主要提供了服务注册和服务发现这两大核心功能。 注册中心可以说是微服务架构中的“通讯录”&#xff0c;它记录了服务和服务地址的映射关系。 常用的注册中心有Zookeep…

UTC和北京时间

influxdb 的时间为UTC和北京时间相差8小时&#xff0c;需要经常转化&#xff0c;所以有下面的2个常用时间 public static void main(String[] args) {//北京时间当天0点ZonedDateTime dateTime ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));ZonedDateTime beijin…

OCP Java17 SE Developers 复习题14

答案 C. Since the question asks about putting data into a structured object, the best class would be one that deserializes the data. Therefore, ObjectInputStream is the best choice, which is option C. ObjectWriter, BufferedStream, and ObjectReader are no…

Ubuntu如何给tar.gz文件创建桌面快捷方式

在Ubuntu中&#xff0c;给.tar.gz文件创建URL桌面图标快捷方式或者是启动脚本桌面图标快捷方式可以通过创建一个.desktop文件来实现。.desktop文件是Linux系统中用于定义应用程序启动器的文件格式&#xff0c;它们通常包含图标、名称和执行命令等信息。以下是创建.tar.gz文件的…

汇智知了堂走进宜宾学院,共话国产化信创未来!

在春意盎然的四月&#xff0c;汇智知了堂以其深厚的品牌底蕴和卓越的教育品质&#xff0c;再次展现了其在教育领域的领先地位。4月18日&#xff0c;汇智知了堂走进宜宾学院&#xff0c;为广大学子带来了一场关于国产化信创时代的技术变革与专业学习建议的讲座。 汇智知了堂作…

springboot Logback 不同环境,配置不同的日志输出路径

1.背景&#xff1a; mac 笔记本开发&#xff0c;日志文件写到/data/logs/下&#xff0c;控制台报出&#xff1a;Failed to create parent directories for [/data/logs/........... 再去手动在命令窗口创建文件夹data&#xff0c;报Read-only file system 2.修改logback-spri…