C# CvDnn部署CoupledTPS实现旋转图像矫正

news2024/9/24 1:26:19

C# CvDnn部署CoupledTPS实现旋转图像矫正

目录

说明

效果

模型信息

项目

代码

下载


说明

TPAMI2024 - Semi-Supervised Coupled Thin-Plate Spline Model for Rotation Correction and Beyond

github地址:https://github.com/nie-lang/CoupledTPS

代码实现参考:https://github.com/hpc203/CoupledTPS-opencv-dnn

效果

模型信息

feature_extractor.onnx

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

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

Outputs
-------------------------
name:feature
tensor:Float[1, 256, 24, 32]
---------------------------------------------------------------

regressnet.onnx

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

Inputs
-------------------------
name:feature
tensor:Float[1, 256, 24, 32]
---------------------------------------------------------------

Outputs
-------------------------
name:mesh_motion
tensor:Float[1, 7, 9, 2]
---------------------------------------------------------------

项目

代码

Form1.cs

using OpenCvSharp;
using System;
using System.Drawing;
using System.Drawing.Imaging;
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;
        Mat image;

        CoupledTPS_RotationNet rotationNet;
        int iter_num = 3;

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory =Application.StartupPath+"\\test_img\\";
            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 void button2_Click(object sender, EventArgs e)
        {
            if (image_path == "")
            {
                return;
            }
            button2.Enabled = false;
            pictureBox2.Image = null;
            textBox1.Text = "";
            Application.DoEvents();
            //读图片
            image = new Mat(image_path);
            dt1 = DateTime.Now;
            Mat result_image = rotationNet.detect(image, iter_num);
            dt2 = DateTime.Now;
            Cv2.CvtColor(result_image, result_image, ColorConversionCodes.BGR2RGB);
            pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
            textBox1.Text = "推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms";
            button2.Enabled = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            rotationNet = new CoupledTPS_RotationNet("model/feature_extractor.onnx", "model/regressnet.onnx");
            image_path = "test_img/00150_-8.4.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 OpenCvSharp;
using System;
using System.Drawing;
using System.Drawing.Imaging;
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;
        Mat image;

        CoupledTPS_RotationNet rotationNet;
        int iter_num = 3;

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory =Application.StartupPath+"\\test_img\\";
            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 void button2_Click(object sender, EventArgs e)
        {
            if (image_path == "")
            {
                return;
            }
            button2.Enabled = false;
            pictureBox2.Image = null;
            textBox1.Text = "";
            Application.DoEvents();
            //读图片
            image = new Mat(image_path);
            dt1 = DateTime.Now;
            Mat result_image = rotationNet.detect(image, iter_num);
            dt2 = DateTime.Now;
            Cv2.CvtColor(result_image, result_image, ColorConversionCodes.BGR2RGB);
            pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
            textBox1.Text = "推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms";
            button2.Enabled = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            rotationNet = new CoupledTPS_RotationNet("model/feature_extractor.onnx", "model/regressnet.onnx");
            image_path = "test_img/00150_-8.4.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);
            }
        }
    }
}

CoupledTPS_RotationNet.cs

using OpenCvSharp;
using OpenCvSharp.Dnn;
using System.Collections.Generic;
using System.Linq;

namespace Onnx_Demo
{
    public class CoupledTPS_RotationNet
    {

        int input_height = 384;
        int input_width = 512;
        int grid_h = 6;
        int grid_w = 8;
        Mat grid = new Mat();
        Mat W_inv = new Mat();

        Net feature_extractor;
        Net regressNet;

        public CoupledTPS_RotationNet(string modelpatha, string modelpathb)
        {
            feature_extractor = CvDnn.ReadNet(modelpatha);
            regressNet = CvDnn.ReadNet(modelpathb);
            tps2flow.get_norm_rigid_mesh_inv_grid(ref grid, ref W_inv, input_height, input_width, grid_h, grid_w);
        }

        unsafe public Mat detect(Mat srcimg, int iter_num)
        {
            Mat img = new Mat();
            Cv2.Resize(srcimg, img, new Size(input_width, input_height));
            img.ConvertTo(img, MatType.CV_32FC3, 1.0 / 127.5d, -1.0d);

            Mat input_tensor = CvDnn.BlobFromImage(img);

            feature_extractor.SetInput(input_tensor);

            Mat[] feature_oris = new Mat[1] { new Mat() };
            string[] outBlobNames = feature_extractor.GetUnconnectedOutLayersNames().ToArray();
            feature_extractor.Forward(feature_oris, outBlobNames);
            Mat feature = feature_oris[0].Clone();

            int[] shape = { 1, 2, input_height, input_width };
            Mat flow = Mat.Zeros(MatType.CV_32FC1, shape);

            List<Mat> flow_list = new List<Mat>();
            for (int i = 0; i < iter_num; i++)
            {
                regressNet.SetInput(feature);
                Mat[] mesh_motions = new Mat[1] { new Mat() };
                regressNet.Forward(mesh_motions, regressNet.GetUnconnectedOutLayersNames().ToArray());

                float* offset = (float*)mesh_motions[0].Data;

                Mat tp = new Mat();

                tps2flow.get_ori_rigid_mesh_tp(ref tp, offset, input_height, input_width, grid_h, grid_w);

                Mat T = W_inv * tp;   //_solve_system
                T = T.T();    //舍弃batchsize

                Mat T_g = T * grid;

                Mat delta_flow = new Mat();

                tps2flow._transform(T_g, grid, input_height, input_width, ref delta_flow);

                if (i == 0)
                {
                    flow += delta_flow;

                }
                else
                {
                    Mat warped_flow = new Mat();
                    grid_sample.warp_with_flow(flow, delta_flow, ref warped_flow);

                    flow = delta_flow + warped_flow;
                }
                flow_list.Add(flow.Clone());

                if (i < (iter_num - 1))
                {
                    int fea_h = feature.Size(2);
                    int fea_w = feature.Size(3);
                    float scale_h = (float)fea_h / flow.Size(2);
                    float scale_w = (float)fea_w / flow.Size(3);

                    Mat down_flow = new Mat();
                    upsample.UpSamplingBilinear(flow, ref down_flow, fea_h, fea_w, true, scale_h, scale_w);

                    for (int h = 0; h < fea_h; h++)
                    {
                        for (int w = 0; w < fea_w; w++)
                        {
                            float* p_w = (float*)down_flow.Ptr(0, 0, h);
                            float temp_w = p_w[w];
                            temp_w = temp_w * scale_w;
                            p_w[w] = temp_w;

                            float* p_h = (float*)down_flow.Ptr(0, 1, h);
                            float temp_h = p_h[w];
                            temp_h = temp_h * scale_h;
                            p_h[w] = temp_h;

                        }
                    }
                    feature.Release();
                    feature = new Mat();
                    grid_sample.warp_with_flow(feature_oris[0], down_flow, ref feature);
                }
            }
            Mat correction_final = new Mat();

            grid_sample.warp_with_flow(input_tensor, flow_list[iter_num - 1], ref correction_final);

            Mat correction_img = grid_sample.convert4dtoimage(correction_final);

            return correction_img;

        }
    }
}

下载

源码下载

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

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

相关文章

【SpringCloud应用框架】Nacos命名空间、分组和DataID三者关系

第五章 Spring Cloud Alibaba Nacos之命名空间、分组和DataID三者关系 文章目录 一、名词解释三者关系 二、切换不同环境DataID方案Group方案Namespace空间方案 一、名词解释 命名空间&#xff08;Namespace&#xff09; ​用于进行租户粒度的配置隔离。不同的命名空间下&…

C++ 智能指针使用不当导致内存泄漏问题

shared_ptr相互嵌套导致循环引用 代码示例 #include <iostream> #include <memory> using namespace std;class B;class A { public:std::shared_ptr<B> b_ptr;~A() { std::cout << "A destroyed\n"; } };class B { public:std::shared_pt…

优选算法之技巧(一):双指针一:移位0与复写0

引用&#xff1a;我们之前学过快排&#xff0c;首先用三元取中&#xff0c;找(key)&#xff0c;然后就用到了双指针的方法来进行交换排序&#xff0c;那我们今天要讲的双指针其实大同小异&#xff0c;无非在数组中就变成了下标。 题一&#xff1a; 给定一个数组 nums&#xf…

云平台教程 | 手把手教你主成分分析PCA的可视化

爱基百客云平台小工具使用 1.1 爱基百客云平台之PCA分析 1.2 PCA分析原理 1.3 参数设置 1.4 任务查看 1.5 结果 1.5.1 PCA图 01 爱基百客云平台小工具使用 首先&#xff0c;打开爱基百客官网&#xff1a;http://www.igenebook.com&#xff1b;点击菜单栏最右侧“云平台”按钮…

藏汉翻译通工具推荐使用《藏文翻译词典》App:藏族文化的掌上宝典,帮助你了解学习藏语反义词近义词和藏文作文!

如果你正在学习藏语&#xff0c;遇到不同地区的发音不同时&#xff0c;卫藏语、安多语和康巴语&#xff0c;那么你需要一款好用的翻译和语音朗读工具&#xff0c;帮助你掌握藏语。 如果你正在用藏文写作文&#xff0c;发现一些词汇不会时&#xff0c;需要使用藏文词典&#xf…

盘点效率工具RunFlow那些容易被忽略的功能

本文我们将带您了解RunFlow有哪些容易被忽略、但是又非常实用的功能。 固定工作窗口 您还可以通过双击 Ctrl 键来切换窗口固定状态&#xff0c;您也可以在 热点事件 设置页面自定义该快捷键。 预览菜单内容 用浏览器打开剪贴板复制的URL 多行输入 按 CtrlEnter 或 ShiftEnter …

C语言 -- 深入理解指针(二)

C语言 -- 深入理解指针&#xff08;二&#xff09; 1. 数组名的理解2. 使用指针访问数组3. 一维数组传参的本质4. 冒泡排序5. 二级指针6. 指针数组7. 指针数组模拟二维数组8. 字符指针变量9. 数组指针变量2.1数组指针变量是什么&#xff1f;2.2 数组指针变量怎么初始化 10. 二维…

海外媒体发稿-全媒体百科

全球知名媒体机构 在全球范围内&#xff0c;有许多知名的新闻机构负责报道世界各地的新闻事件。以下是一些国外常见的媒体机构&#xff1a; AP&#xff08;美联社&#xff09;合众国际社&#xff08;UPI&#xff09;AFP(法新社)EFE&#xff08;埃菲通讯社&#xff09;Europa …

【vue】下载 打印 pdf (问题总结)- 持续更新ing

这里是目录标题 一、pdf1.查看 下载一、pdf 1.查看 下载 样式 Code<template><div><el-table :data="pdfList" style="width: 100%" border ><el-table-columnprop="index"label="序号"width="80"ali…

JVM:介绍

文章目录 一、什么是JVM二、JVM的功能1、解释和运行2、内存管理3、即时编译 三、常见的JVM四、Java虚拟机规范五、HotSpot发展历程 一、什么是JVM JVM的全称为Java Virtual Machine&#xff0c;Java虚拟机。本质上是一个运行在计算机上的程序&#xff0c;职责是运行Java字节码…

气膜体育馆作为临时赛场有哪些优势—轻空间

一、气膜体育馆简介 气膜体育馆是一种利用气膜技术建造的室内场馆&#xff0c;其结构主要由高强度膜材、充气系统和钢缆固定系统组成。通过向膜体内部充气&#xff0c;使其形成稳定的内部压力来支撑整个建筑结构。气膜体育馆因其快速建设、环保节能、灵活多样等优点&#xff0c…

tqdm进度条函数使用 python

1.作用&#xff1a; 通过使用 tqdm &#xff0c;可以让您在处理大量数据或长时间运行的循环时&#xff0c;更好地了解程序的执行进度&#xff0c;增强用户体验。 2.使用 ---可以使用 pip install tqdm 进行安装。 ---tqdm.tqdm(iterator可迭代对象&#xff0c;desc描述符&…

数据中台设计书及建设指南(中台及大数据解决技术方案)

1. 中台概念 2. 推动企业组织模式演进 3. 建设方法 4 .中台内容 5. 数据安全体系 中台内容围绕数据中台建设评估、整体框架、数据采集&#xff0c;结构化、半结构化、非结构化的数据采集&#xff0c;数据计算能力、存储计算引擎、数据架构、数据挖掘、各种不同数据层建设、模型…

7月8号直播预告 | 全国产EtherCAT运动控制器ZMC432HG及其EtherCAT驱动器与控制器常用回零模式介绍

EtherCAT运动控制边缘控制器是工业互联网的关键组件之一&#xff0c;结合丰富的运动控制功能、实时数据采集、处理和本地计算等&#xff0c;具备高度灵活的可编程性和出色的运动控制性能&#xff0c;为运动控制协同工业互联网应用带来巨大市场潜力&#xff0c;同时也使其成为企…

spark shuffle写操作——SortShuffleWriter

写入的简单流程&#xff1a; 1.生成ExternalSorter对象 2.将消息都是插入ExternalSorter对象中 3.获取到mapOutputWriter&#xff0c;将中间产生的临时文件合并到一个临时文件 4.生成最后的data文件和index文件 可以看到写入的重点类是ExternalSorter对象 ExternalSorter 基…

关于振动盘正反料下料逻辑编写

写在前文 借鉴某个程序的逻辑套路写的 1.就是第一个料是正方向&#xff0c;第二个料是反方向。 (* 基础逻辑应该都差不多&#xff0c;这个是一个振动盘&#xff0c;振动盘的末端是一个上下对射的感应器&#xff0c;这个感应器的作用是对射感应到物料的到位信号&#xff0c;末端…

网安加·百家讲坛 | 关昕健:新时代企业数据安全运营思路

作者简介&#xff1a;关昕健&#xff0c;某运营商安全专家&#xff0c;2015年获CISSP认证&#xff0c;长期负责企业安全运营工作&#xff0c;关注国内外数据安全动态与解决方案&#xff0c;持续开展数据安全运营实践。 近年来&#xff0c;随着《数据安全法》的出台和国家数据局…

怎么将视频翻译免费?这篇文章告诉你5个视频翻译的方法

在探索不同文化的经典影视剧时&#xff0c;我们常常被那些精彩绝伦的台词深深吸引。 然而&#xff0c;难以理解的外语符号让我们难以完全领略其魅力。不过&#xff0c;如果你认识免费视频翻译软件的话&#xff0c;那将这些经典台词从陌生的外语符号变成直观的母语表达&#xf…

Git注释规范

主打一个有用 代码的提交规范参考如下&#xff1a; init:初始化项目feat:新功能&#xff08;feature&#xff09;fix:修补bugdocs:文档&#xff08;documentation&#xff09;style:格式&#xff08;不影响代码运行的变动&#xff09;refactor:重构&#xff08;即不是新增功能…

【双出版加持!录用率高!见刊、检索更稳定!】第六届结构抗震与土木工程研究国际学术会议 (ICSSCER 2024,8月16-18)

随着社会的发展&#xff0c;城市规模的不断扩大&#xff0c;建筑形态也趋于多样化和复杂化&#xff0c;建筑结构形式逐渐由规则简单向高层、大跨甚至特殊复杂的方向发展。而房屋建筑是人们正常生活和生产活动的基本场所&#xff0c;房屋建筑结构的安全必须得到充分保障。但是&a…