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

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

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

目录

介绍

效果

模型信息

项目

代码

下载


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

介绍

github地址:https://github.com/xinyu1205/recognize-anything

Open-source and strong foundation image recognition models.

onnx模型下载地址:https://huggingface.co/CannotFindObject/RAM_ONNX

效果

模型信息

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

            // 输入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]) });
            }
        }

    }
}

下载

源码下载(带模型)

模型下载

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

相关文章

  • [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。由于使用了二进......
  • Qt5.12配置OpenCV教程
    在开发图像处理和计算机视觉应用时,QT和OpenCV是两个不可或缺的工具。QT为我们提供了丰富的图形界面设计功能,而OpenCV则提供了强大的图像处理算法。那么,如何将这两者完美结合呢?本文将为你详细解析QT5.12与OpenCV的配置过程,让你轻松上手!一、软件下载1、QT 5.12.9下载地址:......
  • C++图书管理案例
    Book类存储一本图书信息。classBook{public:stringbookId;stringtitle;floatprice;//构造函数Book(stringmyBookId,stringmyTitle,floatmyPrice){bookId=myBookId;title=myTitle;price=myPrice;......