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.hqwc.cn/news/309388.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

20231229在Firefly的AIO-3399J开发板的Android11使用挖掘机的DTS配置单前后摄像头ov13850

20231229在Firefly的AIO-3399J开发板的Android11使用挖掘机的DTS配置单前后摄像头ov13850 2023/12/29 11:10 开发板&#xff1a;Firefly的AIO-3399J【RK3399】 SDK&#xff1a;rk3399-android-11-r20211216.tar.xz【Android11】 Android11.0.tar.bz2.aa【ToyBrick】 Android11.…

Spring Boot学习随笔- 集成MyBatis-Plus(二)条件查询QueryWrapper、聚合函数的使用、Lambda条件查询

学习视频&#xff1a;【编程不良人】Mybatis-Plus整合SpringBoot实战教程,提高的你开发效率,后端人员必备! 查询方法详解 普通查询 // 根据主键id去查询单个结果的。 Test public void selectById() {User user userMapper.selectById(1739970502337392641L);System.out.print…

JAVA-集合

JAVA-集合 整体结构&#xff1a; Collection collection &#xff08;以实现子类ArrayList为例&#xff1a;&#xff09; 存放类型为 Object&#xff0c;根据实现类的不同&#xff1b;其存放的元素可重复可 不重复&#xff1b; 有序或无序 迭代器 Iterator对象即为迭代器…

基于huffman编解码的图像压缩算法matlab仿真

目录 1.算法运行效果图预览 2.算法运行软件版本 3.部分核心程序 4.算法理论概述 4.1 Huffman编码算法步骤 4.2 Huffman编码的数学原理 4.3 基于Huffman编解码的图像压缩 5.算法完整程序工程 1.算法运行效果图预览 2.算法运行软件版本 matlab2022a 3.部分核心程序 ..…

【Android Gradle 插件】ProductFlavor 配置 ( ProductFlavor 引入 | ProductFlavor 参考文档地址 )

Android Plugin DSL Reference 参考文档 : 文档主页 : Android Plugin 2.3.0 DSL Reference android 模块配置文档 : AppExtension - Android Plugin 2.3.0 DSL Reference ProductFlavor 文档 : ProductFlavor - Android Plugin 2.3.0 DSL Reference 一、ProductFlavor 配置…

【Unity】【FBX】如何将FBX模型导入Unity

【背景】 网上能够找到不少不错的FBX模型资源&#xff0c;大大加速游戏开发时间。如何将这些FBX导入Unity呢&#xff1f; 【步骤】 打开Unity项目文件&#xff0c;进入场景。 点击Projects面板&#xff0c;右键选择Import New Assets 选中FBX文件后导入。Assets文件夹中就会…

蚂蚁实习一面面经

蚂蚁实习一面面经 希望可以帮助到大家 tcp建立连接为什么要三次握手&#xff1f; 三次握手的过程 注意&#xff1a;三次握手的最主要目的是保证连接是双工的&#xff0c;可靠更多的是通过重传机制来保证的 所谓三次握手&#xff0c;即建立TCP连接&#xff0c;需要客户端和…

竞赛保研 基于机器学习与大数据的糖尿病预测

文章目录 1 前言1 课题背景2 数据导入处理3 数据可视化分析4 特征选择4.1 通过相关性进行筛选4.2 多重共线性4.3 RFE&#xff08;递归特征消除法&#xff09;4.4 正则化 5 机器学习模型建立与评价5.1 评价方式的选择5.2 模型的建立与评价5.3 模型参数调优5.4 将调参过后的模型重…

基于CNN神经网络的手写字符识别实验报告

作业要求 具体实验内容根据实际情况自拟&#xff0c;可以是传统的BP神经网络&#xff0c;Hopfield神经网络&#xff0c;也可以是深度学习相关内容。 数据集自选&#xff0c;可以是自建数据集&#xff0c;或MNIST&#xff0c;CIFAR10等公开数据集。 实验报告内容包括但不限于&am…

Linux - 记录问题:怎么通过安装包的方式安装gRPC

适用场景 当docker 构建环境不能链接到github 的时候&#xff0c;就可以使用本地构建的方式 完成对应服务的构建需求。 参考案例 使用本地安装包的方式安装 gRPC 注意&#xff1a; 在Docker构建过程中&#xff0c;某些软件包可能会尝试配置时区&#xff0c;这通常需要交互式…

攻防技术1-网络攻击(HCIP)

目录 一、网络攻击方式分类 1、被动攻击&#xff1a; 2、主动攻击&#xff1a; 3、中间人攻击&#xff1a; 二、网络攻击报文类型分类&#xff1a; 1、流量型攻击 2、单包攻击 三、流量型攻击防范技术 1、DNS Request Flood攻击 攻击原理 DNS交互过程 2、TCP类报文…

X210 Linux开发板挂载NFS文件系统

网络搭建 采用“路由器”“有线网”来将Linux开发板和Ubuntu虚拟机连接在同一个局域网中。具体接线如下&#xff1a; Linux开发板通过网线直接连接到“路由器”的LAN接口上&#xff0c;然后笔记本电脑通过Wifi与路由器连接。 VirtualBox虚拟机网络设置 在”网线“设置界面中…