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

2024-03-14 08:52

本文主要是介绍C# RAM Stable Diffusion 提示词反推 Onnx Demo,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

介绍

效果

模型信息

项目

代码

下载


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

介绍

github地址:GitHub - xinyu1205/recognize-anything: Open-source and strong foundation image recognition models.

Open-source and strong foundation image recognition models.

效果

模型信息

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

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

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

项目

代码

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.Runtime.InteropServices;
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 sbTags = new StringBuilder();
        StringBuilder sbTagsCN = new StringBuilder();
        StringBuilder sb = new StringBuilder();

        public string[] class_names;

        List<Tag> ltTag = new List<Tag>();

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

        float[] mean = { 0.485f, 0.456f, 0.406f };
        float[] std = { 0.229f, 0.224f, 0.225f };

        public void Normalize(Mat src)
        {
            src.ConvertTo(src, MatType.CV_32FC3, 1.0 / 255);
            Mat[] bgr = src.Split();
            for (int i = 0; i < bgr.Length; ++i)
            {
                bgr[i].ConvertTo(bgr[i], MatType.CV_32FC1, 1 / std[i], (0.0 - mean[i]) / std[i]);
            }
            Cv2.Merge(bgr, src);
            foreach (Mat channel in bgr)
            {
                channel.Dispose();
            }
        }

        public float[] ExtractMat(Mat src)
        {
            OpenCvSharp.Size size = src.Size();
            int channels = src.Channels();
            float[] result = new float[size.Width * size.Height * channels];
            GCHandle resultHandle = default;
            try
            {
                resultHandle = GCHandle.Alloc(result, GCHandleType.Pinned);
                IntPtr resultPtr = resultHandle.AddrOfPinnedObject();
                for (int i = 0; i < channels; ++i)
                {
                    Mat cmat = new Mat(
                       src.Height, src.Width,
                       MatType.CV_32FC1,
                       resultPtr + i * size.Width * size.Height * sizeof(float));

                    Cv2.ExtractChannel(src, cmat, i);
                    cmat.Dispose();
                }
            }
            finally
            {
                resultHandle.Free();
            }
            return result;
        }

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

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

            image = new Mat(image_path);

            //图片缩放
            Mat resize_image = new Mat();
            Cv2.Resize(image, resize_image, new OpenCvSharp.Size(384, 384));

            Normalize(resize_image);

            var data = ExtractMat(resize_image);

            resize_image.Dispose();
            image.Dispose();

            // 输入Tensor
            input_tensor = new DenseTensor<float>(data, new[] { 1, 3, 384, 384 });

            //将 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<Tag> tags = new List<Tag>(ltTag);

            List<Tag> topTags = new List<Tag>();
            for (int i = 0; i < scores.Length; i++)
            {
                if (scores[i] > tags[i].Threshold)
                {
                    tags[i].Score = scores[i];
                    topTags.Add(tags[i]);
                }
            }
            topTags.OrderByDescending(x => x.Score).ToList();

            foreach (var item in topTags)
            {
                sbTagsCN.Append(item.NameCN + ",");
                sbTags.Append(item.Name + ",");
            }
            sbTagsCN.Length--;
            sbTags.Length--;

            sb.AppendLine("Tags:" + sbTags.ToString());
            sb.AppendLine("标签:" + sbTagsCN.ToString());
            sb.AppendLine("------------------");
            sb.AppendLine("推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms");
            textBox1.Text = sb.ToString();
            button2.Enabled = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            model_path = "model/ram.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/1.jpg";
            pictureBox1.Image = new Bitmap(image_path);
            image = new Mat(image_path);

            string[] thresholdLines = File.ReadAllLines("model/ram_tag_list_threshold.txt");
            string[] tagChineseLines = File.ReadAllLines("model/ram_tag_list_chinese.txt");
            string[] tagLines = File.ReadAllLines("model/ram_tag_list.txt");

            for (int i = 0; i < tagLines.Length; i++)
            {
                ltTag.Add(new Tag { NameCN = tagChineseLines[i], Name = tagLines[i], Threshold = double.Parse(thresholdLines[i]) });
            }
        }

    }
}

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.Runtime.InteropServices;
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 sbTags = new StringBuilder();StringBuilder sbTagsCN = new StringBuilder();StringBuilder sb = new StringBuilder();public string[] class_names;List<Tag> ltTag = new List<Tag>();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);}float[] mean = { 0.485f, 0.456f, 0.406f };float[] std = { 0.229f, 0.224f, 0.225f };public void Normalize(Mat src){src.ConvertTo(src, MatType.CV_32FC3, 1.0 / 255);Mat[] bgr = src.Split();for (int i = 0; i < bgr.Length; ++i){bgr[i].ConvertTo(bgr[i], MatType.CV_32FC1, 1 / std[i], (0.0 - mean[i]) / std[i]);}Cv2.Merge(bgr, src);foreach (Mat channel in bgr){channel.Dispose();}}public float[] ExtractMat(Mat src){OpenCvSharp.Size size = src.Size();int channels = src.Channels();float[] result = new float[size.Width * size.Height * channels];GCHandle resultHandle = default;try{resultHandle = GCHandle.Alloc(result, GCHandleType.Pinned);IntPtr resultPtr = resultHandle.AddrOfPinnedObject();for (int i = 0; i < channels; ++i){Mat cmat = new Mat(src.Height, src.Width,MatType.CV_32FC1,resultPtr + i * size.Width * size.Height * sizeof(float));Cv2.ExtractChannel(src, cmat, i);cmat.Dispose();}}finally{resultHandle.Free();}return result;}private void button2_Click(object sender, EventArgs e){if (image_path == ""){return;}button2.Enabled = false;textBox1.Text = "";sb.Clear();sbTagsCN.Clear();sbTags.Clear();Application.DoEvents();image = new Mat(image_path);//图片缩放Mat resize_image = new Mat();Cv2.Resize(image, resize_image, new OpenCvSharp.Size(384, 384));Normalize(resize_image);var data = ExtractMat(resize_image);resize_image.Dispose();image.Dispose();// 输入Tensorinput_tensor = new DenseTensor<float>(data, new[] { 1, 3, 384, 384 });//将 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<Tag> tags = new List<Tag>(ltTag);List<Tag> topTags = new List<Tag>();for (int i = 0; i < scores.Length; i++){if (scores[i] > tags[i].Threshold){tags[i].Score = scores[i];topTags.Add(tags[i]);}}topTags.OrderByDescending(x => x.Score).ToList();foreach (var item in topTags){sbTagsCN.Append(item.NameCN + ",");sbTags.Append(item.Name + ",");}sbTagsCN.Length--;sbTags.Length--;sb.AppendLine("Tags:" + sbTags.ToString());sb.AppendLine("标签:" + sbTagsCN.ToString());sb.AppendLine("------------------");sb.AppendLine("推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms");textBox1.Text = sb.ToString();button2.Enabled = true;}private void Form1_Load(object sender, EventArgs e){model_path = "model/ram.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/1.jpg";pictureBox1.Image = new Bitmap(image_path);image = new Mat(image_path);string[] thresholdLines = File.ReadAllLines("model/ram_tag_list_threshold.txt");string[] tagChineseLines = File.ReadAllLines("model/ram_tag_list_chinese.txt");string[] tagLines = File.ReadAllLines("model/ram_tag_list.txt");for (int i = 0; i < tagLines.Length; i++){ltTag.Add(new Tag { NameCN = tagChineseLines[i], Name = tagLines[i], Threshold = double.Parse(thresholdLines[i]) });}}}
}

下载

源码下载(带模型)

模型下载

这篇关于C# RAM Stable Diffusion 提示词反推 Onnx Demo的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/807885

相关文章

C#比较两个List集合内容是否相同的几种方法

《C#比较两个List集合内容是否相同的几种方法》本文详细介绍了在C#中比较两个List集合内容是否相同的方法,包括非自定义类和自定义类的元素比较,对于非自定义类,可以使用SequenceEqual、... 目录 一、非自定义类的元素比较1. 使用 SequenceEqual 方法(顺序和内容都相等)2.

C#使用DeepSeek API实现自然语言处理,文本分类和情感分析

《C#使用DeepSeekAPI实现自然语言处理,文本分类和情感分析》在C#中使用DeepSeekAPI可以实现多种功能,例如自然语言处理、文本分类、情感分析等,本文主要为大家介绍了具体实现步骤,... 目录准备工作文本生成文本分类问答系统代码生成翻译功能文本摘要文本校对图像描述生成总结在C#中使用Deep

C#从XmlDocument提取完整字符串的方法

《C#从XmlDocument提取完整字符串的方法》文章介绍了两种生成格式化XML字符串的方法,方法一使用`XmlDocument`的`OuterXml`属性,但输出的XML字符串不带格式,可读性差,... 方法1:通过XMLDocument的OuterXml属性,见XmlDocument类该方法获得的xm

C#多线程编程中导致死锁的常见陷阱和避免方法

《C#多线程编程中导致死锁的常见陷阱和避免方法》在C#多线程编程中,死锁(Deadlock)是一种常见的、令人头疼的错误,死锁通常发生在多个线程试图获取多个资源的锁时,导致相互等待对方释放资源,最终形... 目录引言1. 什么是死锁?死锁的典型条件:2. 导致死锁的常见原因2.1 锁的顺序问题错误示例:不同

C#提取PDF表单数据的实现流程

《C#提取PDF表单数据的实现流程》PDF表单是一种常见的数据收集工具,广泛应用于调查问卷、业务合同等场景,凭借出色的跨平台兼容性和标准化特点,PDF表单在各行各业中得到了广泛应用,本文将探讨如何使用... 目录引言使用工具C# 提取多个PDF表单域的数据C# 提取特定PDF表单域的数据引言PDF表单是一

C#实现添加/替换/提取或删除Excel中的图片

《C#实现添加/替换/提取或删除Excel中的图片》在Excel中插入与数据相关的图片,能将关键数据或信息以更直观的方式呈现出来,使文档更加美观,下面我们来看看如何在C#中实现添加/替换/提取或删除E... 在Excandroidel中插入与数据相关的图片,能将关键数据或信息以更直观的方式呈现出来,使文档更

C#实现系统信息监控与获取功能

《C#实现系统信息监控与获取功能》在C#开发的众多应用场景中,获取系统信息以及监控用户操作有着广泛的用途,比如在系统性能优化工具中,需要实时读取CPU、GPU资源信息,本文将详细介绍如何使用C#来实现... 目录前言一、C# 监控键盘1. 原理与实现思路2. 代码实现二、读取 CPU、GPU 资源信息1.

在C#中获取端口号与系统信息的高效实践

《在C#中获取端口号与系统信息的高效实践》在现代软件开发中,尤其是系统管理、运维、监控和性能优化等场景中,了解计算机硬件和网络的状态至关重要,C#作为一种广泛应用的编程语言,提供了丰富的API来帮助开... 目录引言1. 获取端口号信息1.1 获取活动的 TCP 和 UDP 连接说明:应用场景:2. 获取硬

C#使用HttpClient进行Post请求出现超时问题的解决及优化

《C#使用HttpClient进行Post请求出现超时问题的解决及优化》最近我的控制台程序发现有时候总是出现请求超时等问题,通常好几分钟最多只有3-4个请求,在使用apipost发现并发10个5分钟也... 目录优化结论单例HttpClient连接池耗尽和并发并发异步最终优化后优化结论我直接上优化结论吧,

C#使用yield关键字实现提升迭代性能与效率

《C#使用yield关键字实现提升迭代性能与效率》yield关键字在C#中简化了数据迭代的方式,实现了按需生成数据,自动维护迭代状态,本文主要来聊聊如何使用yield关键字实现提升迭代性能与效率,感兴... 目录前言传统迭代和yield迭代方式对比yield延迟加载按需获取数据yield break显式示迭