C# Image Caption

目录

介绍

效果

模型

decoder_fc_nsc.onnx

encoder.onnx

项目

代码

下载


C# Image Caption

介绍

地址:https://github.com/ruotianluo/ImageCaptioning.pytorch

I decide to sync up this repo and self-critical.pytorch. (The old master is in old master branch for archive)

效果

模型

decoder_fc_nsc.onnx

Inputs
-------------------------
name:fc_feats
tensor:Float[1, 2048]
---------------------------------------------------------------

Outputs
-------------------------
name:seq
tensor:Int64[1, 20]
name:logprobs
tensor:Float[1, 20, 9488]
---------------------------------------------------------------

encoder.onnx

Inputs
-------------------------
name:img
tensor:Float[1, 3, 640, 640]
---------------------------------------------------------------

Outputs
-------------------------
name:fc
tensor:Float[2048]
---------------------------------------------------------------

项目

代码

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

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

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

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

        Tensor<Int64> result_tensors;

        Net net;

        int feat_len;
        int D;
        int inpWidth = 640;
        int inpHeight = 640;
        float[] mean = new float[] { 0.485f, 0.456f, 0.406f };
        float[] std = new float[] { 0.229f, 0.224f, 0.225f };

        Dictionary<string, string> ix_to_word = new Dictionary<string, string>();

        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);
            pictureBox2.Image = null;
        }

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

            button2.Enabled = false;
            pictureBox2.Image = null;
            textBox1.Text = "";
            pictureBox2.Image = null;
            Application.DoEvents();

            //图片缩放
            image = new Mat(image_path);

            Mat temp_image = new Mat();
            Cv2.Resize(image, temp_image, new OpenCvSharp.Size(inpWidth, inpHeight));
            Normalize(temp_image);

            Mat blob = CvDnn.BlobFromImage(temp_image);

            //配置图片输入数据
            net.SetInput(blob);

            Mat result_mat = net.Forward();

            float* ptr_feat = (float*)result_mat.Data;

            for (int i = 0; i < 2048; i++)
            {
                input_tensor[0, i] = ptr_feat[i];
            }

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

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

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

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

            Int64[] result_array = result_tensors.ToArray();

            string words = "";
            for (int k = 0; k < D; k++)
            {
                if (result_array[k] > 0)
                {
                    if (words.Length > 0)
                    {
                        words += " ";
                    }
                    words += ix_to_word[result_array[k].ToString()];
                }
                else
                {
                    break;
                }
            }

            result_image = image.Clone();

            Cv2.PutText(result_image, words
                , new OpenCvSharp.Point(10, 60)
                , HersheyFonts.HersheySimplex
                , 1
                , new Scalar(0, 0, 255)
                , 2
                );

            pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());

            textBox1.Text = words;

            button2.Enabled = true;
        }

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

        private void Form1_Load(object sender, EventArgs e)
        {
            startupPath = System.Windows.Forms.Application.StartupPath;

            model_path = "model/decoder_fc_nsc.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模型文件的路径

            // 输入Tensor
            input_tensor = new DenseTensor<float>(new[] { 1, 2048 });
            // 创建输入容器
            input_container = new List<NamedOnnxValue>();

            feat_len = 2048;
            D = 20;

            //初始化网络类,读取本地模型
            net = CvDnn.ReadNetFromOnnx("model/encoder.onnx");

            StreamReader sr = new StreamReader("model/vocab.txt");
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                ix_to_word.Add(line.Split(':')[0], line.Split(':')[1]);
            }

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

        private void pictureBox1_DoubleClick(object sender, EventArgs e)
        {
            Common.ShowNormalImg(pictureBox1.Image);
        }

        private void pictureBox2_DoubleClick(object sender, EventArgs e)
        {
            Common.ShowNormalImg(pictureBox2.Image);
        }

        SaveFileDialog sdf = new SaveFileDialog();
        private void button3_Click(object sender, EventArgs e)
        {
            if (pictureBox2.Image == null)
            {
                return;
            }
            Bitmap output = new Bitmap(pictureBox2.Image);
            sdf.Title = "保存";
            sdf.Filter = "Images (*.jpg)|*.jpg|Images (*.png)|*.png|Images (*.bmp)|*.bmp|Images (*.emf)|*.emf|Images (*.exif)|*.exif|Images (*.gif)|*.gif|Images (*.ico)|*.ico|Images (*.tiff)|*.tiff|Images (*.wmf)|*.wmf";
            if (sdf.ShowDialog() == DialogResult.OK)
            {
                switch (sdf.FilterIndex)
                {
                    case 1:
                        {
                            output.Save(sdf.FileName, ImageFormat.Jpeg);
                            break;
                        }
                    case 2:
                        {
                            output.Save(sdf.FileName, ImageFormat.Png);
                            break;
                        }
                    case 3:
                        {
                            output.Save(sdf.FileName, ImageFormat.Bmp);
                            break;
                        }
                    case 4:
                        {
                            output.Save(sdf.FileName, ImageFormat.Emf);
                            break;
                        }
                    case 5:
                        {
                            output.Save(sdf.FileName, ImageFormat.Exif);
                            break;
                        }
                    case 6:
                        {
                            output.Save(sdf.FileName, ImageFormat.Gif);
                            break;
                        }
                    case 7:
                        {
                            output.Save(sdf.FileName, ImageFormat.Icon);
                            break;
                        }

                    case 8:
                        {
                            output.Save(sdf.FileName, ImageFormat.Tiff);
                            break;
                        }
                    case 9:
                        {
                            output.Save(sdf.FileName, ImageFormat.Wmf);
                            break;
                        }
                }
                MessageBox.Show("保存成功,位置:" + sdf.FileName);
            }
        }
    }
}

using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using OpenCvSharp;
using OpenCvSharp.Dnn;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows.Forms;namespace ImageCaption
{public partial class Form1 : Form{public Form1(){InitializeComponent();}string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";string image_path = "";string startupPath;string classer_path;DateTime dt1 = DateTime.Now;DateTime dt2 = DateTime.Now;string model_path;Mat image;Mat result_image;SessionOptions options;InferenceSession onnx_session;Tensor<float> input_tensor;List<NamedOnnxValue> input_container;IDisposableReadOnlyCollection<DisposableNamedOnnxValue> result_infer;DisposableNamedOnnxValue[] results_onnxvalue;Tensor<Int64> result_tensors;Net net;int feat_len;int D;int inpWidth = 640;int inpHeight = 640;float[] mean = new float[] { 0.485f, 0.456f, 0.406f };float[] std = new float[] { 0.229f, 0.224f, 0.225f };Dictionary<string, string> ix_to_word = new Dictionary<string, string>();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);pictureBox2.Image = null;}private unsafe void button2_Click(object sender, EventArgs e){if (image_path == ""){return;}button2.Enabled = false;pictureBox2.Image = null;textBox1.Text = "";pictureBox2.Image = null;Application.DoEvents();//图片缩放image = new Mat(image_path);Mat temp_image = new Mat();Cv2.Resize(image, temp_image, new OpenCvSharp.Size(inpWidth, inpHeight));Normalize(temp_image);Mat blob = CvDnn.BlobFromImage(temp_image);//配置图片输入数据net.SetInput(blob);Mat result_mat = net.Forward();float* ptr_feat = (float*)result_mat.Data;for (int i = 0; i < 2048; i++){input_tensor[0, i] = ptr_feat[i];}//将 input_tensor 放入一个输入参数的容器,并指定名称input_container.Add(NamedOnnxValue.CreateFromTensor("fc_feats", input_tensor));//运行 Inference 并获取结果result_infer = onnx_session.Run(input_container);// 将输出结果转为DisposableNamedOnnxValue数组results_onnxvalue = result_infer.ToArray();// 读取第一个节点输出并转为Tensor数据result_tensors = results_onnxvalue[0].AsTensor<Int64>();Int64[] result_array = result_tensors.ToArray();string words = "";for (int k = 0; k < D; k++){if (result_array[k] > 0){if (words.Length > 0){words += " ";}words += ix_to_word[result_array[k].ToString()];}else{break;}}result_image = image.Clone();Cv2.PutText(result_image, words, new OpenCvSharp.Point(10, 60), HersheyFonts.HersheySimplex, 1, new Scalar(0, 0, 255), 2);pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());textBox1.Text = words;button2.Enabled = true;}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();}}private void Form1_Load(object sender, EventArgs e){startupPath = System.Windows.Forms.Application.StartupPath;model_path = "model/decoder_fc_nsc.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模型文件的路径// 输入Tensorinput_tensor = new DenseTensor<float>(new[] { 1, 2048 });// 创建输入容器input_container = new List<NamedOnnxValue>();feat_len = 2048;D = 20;//初始化网络类,读取本地模型net = CvDnn.ReadNetFromOnnx("model/encoder.onnx");StreamReader sr = new StreamReader("model/vocab.txt");string line;while ((line = sr.ReadLine()) != null){ix_to_word.Add(line.Split(':')[0], line.Split(':')[1]);}image_path = "test_img/1.jpg";pictureBox1.Image = new Bitmap(image_path);image = new Mat(image_path);}private void pictureBox1_DoubleClick(object sender, EventArgs e){Common.ShowNormalImg(pictureBox1.Image);}private void pictureBox2_DoubleClick(object sender, EventArgs e){Common.ShowNormalImg(pictureBox2.Image);}SaveFileDialog sdf = new SaveFileDialog();private void button3_Click(object sender, EventArgs e){if (pictureBox2.Image == null){return;}Bitmap output = new Bitmap(pictureBox2.Image);sdf.Title = "保存";sdf.Filter = "Images (*.jpg)|*.jpg|Images (*.png)|*.png|Images (*.bmp)|*.bmp|Images (*.emf)|*.emf|Images (*.exif)|*.exif|Images (*.gif)|*.gif|Images (*.ico)|*.ico|Images (*.tiff)|*.tiff|Images (*.wmf)|*.wmf";if (sdf.ShowDialog() == DialogResult.OK){switch (sdf.FilterIndex){case 1:{output.Save(sdf.FileName, ImageFormat.Jpeg);break;}case 2:{output.Save(sdf.FileName, ImageFormat.Png);break;}case 3:{output.Save(sdf.FileName, ImageFormat.Bmp);break;}case 4:{output.Save(sdf.FileName, ImageFormat.Emf);break;}case 5:{output.Save(sdf.FileName, ImageFormat.Exif);break;}case 6:{output.Save(sdf.FileName, ImageFormat.Gif);break;}case 7:{output.Save(sdf.FileName, ImageFormat.Icon);break;}case 8:{output.Save(sdf.FileName, ImageFormat.Tiff);break;}case 9:{output.Save(sdf.FileName, ImageFormat.Wmf);break;}}MessageBox.Show("保存成功,位置:" + sdf.FileName);}}}
}

下载

源码下载

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/823704.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

最新Redis7哨兵模式(保姆级教学)

一定一定要把云服务器的防火墙打开一定要&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;否则不成功&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&…

java设计模式实战【策略模式+观察者模式+命令模式+组合模式,混合模式在支付系统中的应用】

引言 在代码开发的世界里&#xff0c;理论知识的重要性毋庸置疑&#xff0c;但实战经验往往才是知识的真正试金石。正所谓&#xff0c;“读万卷书不如行万里路”&#xff0c;理论的学习需要通过实践来验证和深化。设计模式作为软件开发中的重要理论&#xff0c;其真正的价值在…

销售转行上位机编程:我的学习与职业经历分享

同学们好&#xff0c;我是杨工&#xff0c;原先是一名销售。 通过在华山编程培训中心学习&#xff0c;成功转行上位机编程&#xff0c;对此我想分享学习和职业经历。 在职业生涯的早期&#xff0c;我并没有考虑将技术融入到我的工作中。然而&#xff0c;在几次创业的失败后&a…

编程羔手解决Maven引入多个版本的依赖包,导致包冲突了

最近升级了些依赖发现有个hutool的方法老报错&#xff0c;java.lang.NoSuchMethodError: cn.hutool.core.util.ObjectUtil.defaultIfNull(Ljava/lang/Object;Ljava/util/function/Supplier;) 在 Maven 项目中&#xff0c;当不同的依赖模块引入 Hutool 的不同版本时&#xff0c…

C++编程中级阶段

目录 1.模版 1.1函数模版 1.1.1函数模版语法 1.1.2函数模版注意事项 1.1.3函数模版案例 1.1.4普通函数与函数模板的区别 1.1.5普通函数与函数模板的调用规则 1.1.6模版的局限性 1.2类模版 2.STL处识 3.STL常用容器 3.1string容器 3.2vector容器 3.3deque容器 3.…

竞赛保研 基于机器视觉的12306验证码识别

文章目录 0 简介1 数据收集2 识别过程3 网络构建4 数据读取5 模型训练6 加入Dropout层7 数据增强8 迁移学习9 结果9 最后 0 简介 &#x1f525; 优质竞赛项目系列&#xff0c;今天要分享的是 基于机器视觉的12306验证码识别 该项目较为新颖&#xff0c;适合作为竞赛课题方向…

Go语言学习第二天

Go语言数组详解 var 数组变量名 [元素数量]Type 数组变量名&#xff1a;数组声明及使用时的变量名。 元素数量&#xff1a;数组的元素数量&#xff0c;可以是一个表达式&#xff0c;但最终通过编译期计算的结果必须是整型数值&#xff0c;元素数量不能含有到运行时才能确认大小…

神经网络:机器学习基础

【一】什么是模型的偏差和方差&#xff1f; 误差&#xff08;Error&#xff09; 偏差&#xff08;Bias&#xff09; 方差&#xff08;Variance&#xff09; 噪声&#xff08;Noise&#xff09;&#xff0c;一般地&#xff0c;我们把机器学习模型的预测输出与样本的真实label…

浅谈数据仓库运营

一、背景 企业每天都会产生大量的数据&#xff0c;随着时间增长&#xff0c;数据会呈现几何增长&#xff0c;尤其在系统基建基础好的公司。好的数据仓库需要提前规划和好的运营&#xff0c;才能支持企业的发展&#xff0c;为企业提供数据分析基础。 二、目标 提高数据仓库存储…

2024 通义语音 AI 技术图景,大模型引领 AI 再进化

自 1956 年达特茅斯会议上&#xff0c;约翰麦卡锡首次提出了“人工智能”这一术语。AI 在此后七十年的发展中呈现脉冲式趋势&#xff0c;每隔 5-10 年会出现一次技术革新和域定。在这一技术探索进程之中&#xff0c;预训练基础模型逐渐成为主流探索方向&#xff0c;受到学术界和…

【机器学习合集】深度生成模型 ->(个人学习记录笔记)

深度生成模型 深度生成模型基础 1. 监督学习与无监督学习 1.1 监督学习 定义 在真值标签Y的指导下&#xff0c;学习一个映射函数F&#xff0c;使得F(X)Y 判别模型 Discriminative Model&#xff0c;即判别式模型&#xff0c;又称为条件模型&#xff0c;或条件概率模型 生…

【力扣100】207.课程表

添加链接描述 class Solution:def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:# 思路是计算每一个课的入度&#xff0c;然后使用队列进行入度为0的元素的进出# 数组&#xff1a;下标是课程号&#xff0c;array[下标]是这个课程的入度# 哈希…

技术探秘:在RISC Zero中验证FHE——RISC Zero应用的DevOps(2)

1. 引言 前序博客&#xff1a; 技术探秘&#xff1a;在RISC Zero中验证FHE——由隐藏到证明&#xff1a;FHE验证的ZK路径&#xff08;1&#xff09; 技术探秘&#xff1a;在RISC Zero中验证FHE——由隐藏到证明&#xff1a;FHE验证的ZK路径&#xff08;1&#xff09; 中&…

一套好的商业模式,助力生意长虹!

在当今竞争激烈的市场环境中&#xff0c;一套好的商业模式对于企业的成功至关重要。一个优秀的商业模式不仅能够提高企业的盈利能力&#xff0c;还能让企业在市场中脱颖而出&#xff0c;实现长期的稳定发展。本文将为您揭示一套神奇的商业模式&#xff0c;帮助您的生意长虹&…

帆软报表如何灵活控制水印的显示

在帆软报表中如果要显示水印,如果要全部都要显示,只需要到决策系统--安装设置中打开水印开关。如果想要某个报表显示水印,可以在设计器的水印设置中为该报表设置水印。 但是如果碰到这种需求,比如某些人或者某些角色需要显示水印,其他人不显示。或者是预览报表需要显示水印…

机器学习系列11:减少过拟合——L1、L2正则化

如果我们注意到模型在训练集上的表现明显优于模型在测试集上的表现&#xff0c;那么这就是模型过拟合了&#xff0c;也称为 high variance。 产生的过拟合的原因是对于给定的训练集数据来说&#xff0c;模型太复杂了。有几种可以减少过拟合的方法&#xff1a; 收集更多的训练数…

Matplotlib ------ 纵坐标科学计数法含义

matplotlib 纵坐标科学计数法含义 引言正文 引言 今天画图时遇到了一个问题&#xff0c;发现纵坐标是科学计数法的表示&#xff0c;但是很难理解它的含义&#xff0c;这里特来记录一下。 正文 我们以下图为例&#xff0c; 由图上我们可以看出&#xff0c;纵坐标显示为 1e-…

pycharm找回误删的文件和目录

昨天不知道做了什么鬼操作&#xff0c;可能是运行了几个git命令&#xff0c;将项目里面的几个文件删除了&#xff0c;有点懵。 我知道pycharm可以找回文件的历史修改记录&#xff0c;但是对于删除的文件能否恢复&#xff0c;一直没试过。 找到删除文件的目录&#xff0c;点击右…

【MySQL】数据库之高级SQL查询语句补充

目录 一、补充正则表达式的查询regexp 二、补充case的用法 三、补充空值和null值的区别 一、补充正则表达式的查询regexp 要知道 在MySQL中使用正则表达式&#xff0c;一定要在前面加上regexp 正则表达式 ^ 匹配文本的开始字符 ‘^bd’ 匹配以 bd 开头的字符串 …

青龙面板的安装

一、安装docker 首先&#xff0c;需要在服务器上安装docker。 没有服务器的可以使用虚拟机&#xff0c;或申请一台三丰云的免费云服务器体验一下&#xff0c;独立IP地址&#xff0c;送免备案服务&#xff0c;可以满足基本的使用&#xff0c;三丰云上还有免费虚拟主机等其他免费…