首页 > 编程语言 >C# danbooru Stable Diffusion 提示词反推 Onnx Demo

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

时间:2024-03-13 13:33:47浏览次数:28  
标签:Diffusion input using C# Onnx image result new path

目录

说明

效果

模型信息

项目

代码

下载 


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]
--------------------------------------------------------------- 

项目

代码

using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Onnx_Demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

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

        SessionOptions options;
        InferenceSession onnx_session;
        Tensor<float> input_tensor;
        List<NamedOnnxValue> input_container;
        IDisposableReadOnlyCollection<DisposableNamedOnnxValue> result_infer;
        DisposableNamedOnnxValue[] results_onnxvalue;

        Tensor<float> result_tensors;

        StringBuilder sb = new StringBuilder();

        public string[] class_names;

        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);

            // 输入Tensor
            input_tensor = new DenseTensor<float>(new[] { 1, 3,image.Height, image.Width });

            // 输入Tensor
            for (int y = 0; y < image.Height; y++)
            {
                for (int x = 0; x < image.Width; x++)
                {
                    input_tensor[0,0, y, x] = image.At<Vec3b>(y, x)[0];
                    input_tensor[0,1, y, x] = image.At<Vec3b>(y, x)[1];
                    input_tensor[0,2, y, x] = image.At<Vec3b>(y, x)[2];
                }
            }

            //将 input_tensor 放入一个输入参数的容器,并指定名称
            input_container.Add(NamedOnnxValue.CreateFromTensor("input", input_tensor));

            dt1 = DateTime.Now;
            //运行 Inference 并获取结果
            result_infer = onnx_session.Run(input_container);
            dt2 = DateTime.Now;

            // 将输出结果转为DisposableNamedOnnxValue数组
            results_onnxvalue = result_infer.ToArray();

            // 读取第一个节点输出并转为Tensor数据
            result_tensors = results_onnxvalue[0].AsTensor<float>();

            var result_array = result_tensors.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("------------------");
            
            // 只取分数最高的
            // float max = result_array.Max();
            // int maxIndex = Array.IndexOf(result_array, max);
            // sb.AppendLine(class_names[maxIndex]+" "+ max.ToString("P2"));
           
            sb.AppendLine("推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms");
            textBox1.Text = sb.ToString();
            button2.Enabled = true;
        }

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

            // 创建输出会话,用于输出模型读取信息
            options = new SessionOptions();
            options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_INFO;
            options.AppendExecutionProvider_CPU(0);// 设置为CPU上运行

            // 创建推理模型类,读取本地模型文件
            onnx_session = new InferenceSession(model_path, options);//model_path 为onnx模型文件的路径
            
            // 创建输入容器
            input_container = new List<NamedOnnxValue>();

            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();
        }

    }
}

using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Onnx_Demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

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

        SessionOptions options;
        InferenceSession onnx_session;
        Tensor<float> input_tensor;
        List<NamedOnnxValue> input_container;
        IDisposableReadOnlyCollection<DisposableNamedOnnxValue> result_infer;
        DisposableNamedOnnxValue[] results_onnxvalue;

        Tensor<float> result_tensors;

        StringBuilder sb = new StringBuilder();

        public string[] class_names;

        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);

            // 输入Tensor
            input_tensor = new DenseTensor<float>(new[] { 1, 3,image.Height, image.Width });

            // 输入Tensor
            for (int y = 0; y < image.Height; y++)
            {
                for (int x = 0; x < image.Width; x++)
                {
                    input_tensor[0,0, y, x] = image.At<Vec3b>(y, x)[0];
                    input_tensor[0,1, y, x] = image.At<Vec3b>(y, x)[1];
                    input_tensor[0,2, y, x] = image.At<Vec3b>(y, x)[2];
                }
            }

            //将 input_tensor 放入一个输入参数的容器,并指定名称
            input_container.Add(NamedOnnxValue.CreateFromTensor("input", input_tensor));

            dt1 = DateTime.Now;
            //运行 Inference 并获取结果
            result_infer = onnx_session.Run(input_container);
            dt2 = DateTime.Now;

            // 将输出结果转为DisposableNamedOnnxValue数组
            results_onnxvalue = result_infer.ToArray();

            // 读取第一个节点输出并转为Tensor数据
            result_tensors = results_onnxvalue[0].AsTensor<float>();

            var result_array = result_tensors.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("------------------");
            
            // 只取分数最高的
            // float max = result_array.Max();
            // int maxIndex = Array.IndexOf(result_array, max);
            // sb.AppendLine(class_names[maxIndex]+" "+ max.ToString("P2"));
           
            sb.AppendLine("推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms");
            textBox1.Text = sb.ToString();
            button2.Enabled = true;
        }

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

            // 创建输出会话,用于输出模型读取信息
            options = new SessionOptions();
            options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_INFO;
            options.AppendExecutionProvider_CPU(0);// 设置为CPU上运行

            // 创建推理模型类,读取本地模型文件
            onnx_session = new InferenceSession(model_path, options);//model_path 为onnx模型文件的路径
            
            // 创建输入容器
            input_container = new List<NamedOnnxValue>();

            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();
        }

    }
}

下载 

源码下载

标签:Diffusion,input,using,C#,Onnx,image,result,new,path
From: https://blog.csdn.net/lw112190/article/details/136677149

相关文章

  • springmvc入门登录功能
    学习springmvc的时候的一个入门功能,登录功能。配置好web框架,导入需要springjar包和springmvc需要的两个jar包,就可以编码了,首先写了登录需要的jsp页面<%@pagecontentType="text/html;charset=UTF-8"language="java"%><html><head><title>Title</title></hea......
  • C# RAM Stable Diffusion 提示词反推 Onnx Demo
    目录介绍效果模型信息项目代码下载C#RAMStableDiffusion提示词反推OnnxDemo介绍github地址:https://github.com/xinyu1205/recognize-anythingOpen-sourceandstrongfoundationimagerecognitionmodels.onnx模型下载地址:https://huggingface.co/CannotFi......
  • [C++]C++函数指针总结
    指针的概念指针是一个特殊的变量,它里面存储的数值被解释成为内存里的一个地址。要搞清一个指针需要搞清指针的四方面的内容:指针的类型,指针所指向的类型,指针的值或者叫指针所指向的内存区,还有指针本身所占据的内存区。让我们分别说明。先声明几个指针放着做例子:例一:int*......
  • [C++]c++ 在项目cpp文件中直接用#pragma comment语句引入,无需配置属性表
    使用语句添加引入库的好处就是无需配置多个属性表,不管是debug模式还是release模式,不管是64位还是32位,几行代码通吃。相对路径:#ifdef_M_X64#pragmacomment(lib,"../../../VC++/DVPCamera64.lib")#else#pragmacomment(lib,"../../../VC++/DVPCamera32.lib")#endif绝......
  • Be Your Own Teacher: Improve thePerformance of Convolutional Neural Networks via
    摘要本文中,提出了一种名为自蒸馏的通用训练框架,该框架通过缩小网络的规模而不是扩大网络的规模,而提高卷积神经网络的性能。传统的知识蒸馏是一种网络之间的知识转换方法,它迫使学生神经网络接近预先训练的教师神经网络的softmax层输出,与此不同,所提出的自蒸馏框架提取网络......
  • C语言入门学习 --- 7.结构体
    文章目录第七章结构体1.结构体的声明1.1结构的基础知识1.2结构的声明1.3结构成员的类型1.4结构体变量的定义和初始化2.结构体成员的访问2.1结构体变量访问成员2.2结构体指针访问指向变量的成员3.结构体传参配套练习:第七章结构体1.结构体类型的声明2.结构体初始......
  • C语言入门学习 --- 9.编程练习题
    1.正整数A和正整数B的最小公倍数是指能被A和B整除的最小的正整数,设计一个算法,求输入A和B的最小公倍数。输入描述:输入两个正整数A和B。输出描述:输出A和B的最小公倍数。输入:57输出:35#include<stdio.h>intmain(){ inta=0; intb=0; inti=0; scanf("%d%......
  • 中间代码生成(Intermediate Code Generation)
    目录在编译器设计中,将高级语言代码(如C、C++、Java等)转换为低级语言(如汇编语言或机器语言)是一个复杂的过程,其中包括对不同类型的语句进行翻译。下面我将简要解释你提到的各种语句的翻译过程:声明语句的翻译:声明语句用于定义变量、类型或函数。在翻译时,编译器会为这些实体在符......
  • 【体验有奖】用 AI 画春天,函数计算搭建 Stable Diffusion WebUI
    人工智能生成内容AIGC(ArtificialIntelligenceGeneratedContent)是当下备受关注的概念之一,是继PGC和UGC之后的新型生产方式。AIGC技术的核心思想是利用人工智能算法生成具有一定创意和质量的内容。例如,根据用户的描述或关键词,即时创作出独特的艺术风格画像,实现个性化的艺术......
  • Golang - grpc和http的区别
    gRPC和HTTP都是网络协议,但是它们之间存在一些显著的区别。1、传输协议HTTP使用文本基础的协议,而gRPC使用的是二进制协议,这意味着gRPC数据包更小,传输效率更高。另外,gRPC使用HTTP/2协议,支持多路复用,从而可以更好地处理并发请求。2、性能差异gRPC在性能方面优于HTTP。由于使用了二进......