C# Onnx segment-anything 分割万物 一键抠图

目录

介绍

效果

模型信息

sam_vit_b_decoder.onnx

sam_vit_b_encoder.onnx

项目

代码

下载


C# Onnx segment-anything 分割万物 一键抠图

介绍

github地址:https://github.com/facebookresearch/segment-anything

The repository provides code for running inference with the SegmentAnything Model (SAM), links for downloading the trained model checkpoints, and example notebooks that show how to use the model. 

效果

C# Onnx segment-anything 分割万物

模型信息

sam_vit_b_decoder.onnx

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

Inputs
-------------------------
name:image_embeddings
tensor:Float[1, 256, 64, 64]
name:point_coords
tensor:Float[1, -1, 2]
name:point_labels
tensor:Float[1, -1]
name:mask_input
tensor:Float[1, 1, 256, 256]
name:has_mask_input
tensor:Float[1]
name:orig_im_size
tensor:Float[2]
---------------------------------------------------------------

Outputs
-------------------------
name:masks
tensor:Float[-1, -1, -1, -1]
name:iou_predictions
tensor:Float[-1, 4]
name:low_res_masks
tensor:Float[-1, -1, -1, -1]
---------------------------------------------------------------

sam_vit_b_encoder.onnx

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

Inputs
-------------------------
name:image
tensor:Float[1, 3, 1024, 1024]
---------------------------------------------------------------

Outputs
-------------------------
name:image_embeddings
tensor:Float[1, 256, 64, 64]
---------------------------------------------------------------

项目

代码

using OpenCvSharp;
using OpenCvSharp.Extensions;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Reflection;
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;

        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;
            pictureBox3.Image = null;

            sam.SetImage(image_path);
            image = new Mat(image_path);
            pictureBox1.Image = new Bitmap(image_path);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            pictureBox3.Image = null;
            button2.Enabled = false;
            Application.DoEvents();
            List<MatInfo> masks_list = sam.GetPointMask(roi);
            if (masks_list.Count>0)
            {
                int MaxInde = 0;
                float maxiou_pred = masks_list[0].iou_pred;
                for (int i = 0; i < masks_list.Count; i++)
                {
                    float temp = masks_list[i].iou_pred;
                    if (temp > maxiou_pred)
                    {
                        MaxInde = i;
                    }
                }
                pictureBox3.Image = BitmapConverter.ToBitmap(masks_list[MaxInde].mask);
            }
            button2.Enabled = true;
        }

        SamInferenceSession sam;

        private void Form1_Load(object sender, EventArgs e)
        {

            string encoderPath = "model/sam_vit_b_encoder.onnx";
            string decoderPath = "model/sam_vit_b_decoder.onnx";

            sam = new SamInferenceSession(encoderPath, decoderPath);
            sam.Initialize();

            image_path = "test_img/test.jpg";

            sam.SetImage(image_path);
            image = new Mat(image_path);
            pictureBox1.Image = new Bitmap(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);
            }
        }

        bool m_mouseDown = false;
        bool m_mouseMove = false;

        System.Drawing.Point startPoint = new System.Drawing.Point();
        System.Drawing.Point endPoint = new System.Drawing.Point();

        Mat currentFrame = new Mat();
        Rect roi = new Rect();

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (pictureBox1.Image == null)
                return;
            if (!m_mouseDown) return;

            m_mouseMove = true;
            endPoint = e.Location;

            pictureBox1.Invalidate();

        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            if (!m_mouseDown || !m_mouseMove)
                return;
            Graphics g = e.Graphics;
            Pen p = new Pen(Color.Blue, 2);
            Rectangle rect = new Rectangle(startPoint.X, startPoint.Y, (endPoint.X - startPoint.X), (endPoint.Y - startPoint.Y));
            g.DrawRectangle(p, rect);

        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (!m_mouseDown || !m_mouseMove)
                return;
            m_mouseDown = false;
            m_mouseMove = false;

            System.Drawing.Point image_startPoint = ConvertCooridinate(startPoint);
            System.Drawing.Point image_endPoint = ConvertCooridinate(endPoint);
            if (image_startPoint.X < 0)
                image_startPoint.X = 0;
            if (image_startPoint.Y < 0)
                image_startPoint.Y = 0;
            if (image_endPoint.X < 0)
                image_endPoint.X = 0;
            if (image_endPoint.Y < 0)
                image_endPoint.Y = 0;
            if (image_startPoint.X > image.Cols)
                image_startPoint.X = image.Cols;
            if (image_startPoint.Y > image.Rows)
                image_startPoint.Y = image.Rows;
            if (image_endPoint.X > image.Cols)
                image_endPoint.X = image.Cols;
            if (image_endPoint.Y > image.Rows)
                image_endPoint.Y = image.Rows;

            label1.Text = String.Format("ROI:({0},{1})-({2},{3})", image_startPoint.X, image_startPoint.Y, image_endPoint.X, image_endPoint.Y);
            int w = (image_endPoint.X - image_startPoint.X);
            int h = (image_endPoint.Y - image_startPoint.Y);
            if (w > 10 && h > 10)
            {
                roi = new Rect(image_startPoint.X, image_startPoint.Y, w, h);
                //Console.WriteLine(String.Format("ROI:({0},{1})-({2},{3})", image_startPoint.X, image_startPoint.Y, image_endPoint.X, image_endPoint.Y));
                //test
                //OpenCvSharp.Point pointinfo = new OpenCvSharp.Point(910, 641);
                //roi = new Rect(pointinfo.X - 160, pointinfo.Y - 430, 380, 940);
                Mat roi_mat = image[roi];
                pictureBox2.Image = BitmapConverter.ToBitmap(roi_mat);
            }
            //pictureBox1.Invalidate();

        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (pictureBox1.Image == null)
                return;
            m_mouseDown = true;
            startPoint = e.Location;
        }

        private System.Drawing.Point ConvertCooridinate(System.Drawing.Point point)
        {
            System.Reflection.PropertyInfo rectangleProperty = this.pictureBox1.GetType().GetProperty("ImageRectangle", BindingFlags.Instance | BindingFlags.NonPublic);
            Rectangle pictureBox = (Rectangle)rectangleProperty.GetValue(this.pictureBox1, null);

            int zoomedWidth = pictureBox.Width;
            int zoomedHeight = pictureBox.Height;

            int imageWidth = pictureBox1.Image.Width;
            int imageHeight = pictureBox1.Image.Height;

            double zoomRatex = (double)(zoomedWidth) / (double)(imageWidth);
            double zoomRatey = (double)(zoomedHeight) / (double)(imageHeight);
            int black_left_width = (zoomedWidth == this.pictureBox1.Width) ? 0 : (this.pictureBox1.Width - zoomedWidth) / 2;
            int black_top_height = (zoomedHeight == this.pictureBox1.Height) ? 0 : (this.pictureBox1.Height - zoomedHeight) / 2;

            int zoomedX = point.X - black_left_width;
            int zoomedY = point.Y - black_top_height;

            System.Drawing.Point outPoint = new System.Drawing.Point();
            outPoint.X = (int)((double)zoomedX / zoomRatex);
            outPoint.Y = (int)((double)zoomedY / zoomRatey);

            return outPoint;
        }

    }
}

using OpenCvSharp;
using OpenCvSharp.Extensions;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Reflection;
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;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;pictureBox3.Image = null;sam.SetImage(image_path);image = new Mat(image_path);pictureBox1.Image = new Bitmap(image_path);}private void button2_Click(object sender, EventArgs e){pictureBox3.Image = null;button2.Enabled = false;Application.DoEvents();List<MatInfo> masks_list = sam.GetPointMask(roi);if (masks_list.Count>0){int MaxInde = 0;float maxiou_pred = masks_list[0].iou_pred;for (int i = 0; i < masks_list.Count; i++){float temp = masks_list[i].iou_pred;if (temp > maxiou_pred){MaxInde = i;}}pictureBox3.Image = BitmapConverter.ToBitmap(masks_list[MaxInde].mask);}button2.Enabled = true;}SamInferenceSession sam;private void Form1_Load(object sender, EventArgs e){string encoderPath = "model/sam_vit_b_encoder.onnx";string decoderPath = "model/sam_vit_b_decoder.onnx";sam = new SamInferenceSession(encoderPath, decoderPath);sam.Initialize();image_path = "test_img/test.jpg";sam.SetImage(image_path);image = new Mat(image_path);pictureBox1.Image = new Bitmap(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);}}bool m_mouseDown = false;bool m_mouseMove = false;System.Drawing.Point startPoint = new System.Drawing.Point();System.Drawing.Point endPoint = new System.Drawing.Point();Mat currentFrame = new Mat();Rect roi = new Rect();private void pictureBox1_MouseMove(object sender, MouseEventArgs e){if (pictureBox1.Image == null)return;if (!m_mouseDown) return;m_mouseMove = true;endPoint = e.Location;pictureBox1.Invalidate();}private void pictureBox1_Paint(object sender, PaintEventArgs e){if (!m_mouseDown || !m_mouseMove)return;Graphics g = e.Graphics;Pen p = new Pen(Color.Blue, 2);Rectangle rect = new Rectangle(startPoint.X, startPoint.Y, (endPoint.X - startPoint.X), (endPoint.Y - startPoint.Y));g.DrawRectangle(p, rect);}private void pictureBox1_MouseUp(object sender, MouseEventArgs e){if (!m_mouseDown || !m_mouseMove)return;m_mouseDown = false;m_mouseMove = false;System.Drawing.Point image_startPoint = ConvertCooridinate(startPoint);System.Drawing.Point image_endPoint = ConvertCooridinate(endPoint);if (image_startPoint.X < 0)image_startPoint.X = 0;if (image_startPoint.Y < 0)image_startPoint.Y = 0;if (image_endPoint.X < 0)image_endPoint.X = 0;if (image_endPoint.Y < 0)image_endPoint.Y = 0;if (image_startPoint.X > image.Cols)image_startPoint.X = image.Cols;if (image_startPoint.Y > image.Rows)image_startPoint.Y = image.Rows;if (image_endPoint.X > image.Cols)image_endPoint.X = image.Cols;if (image_endPoint.Y > image.Rows)image_endPoint.Y = image.Rows;label1.Text = String.Format("ROI:({0},{1})-({2},{3})", image_startPoint.X, image_startPoint.Y, image_endPoint.X, image_endPoint.Y);int w = (image_endPoint.X - image_startPoint.X);int h = (image_endPoint.Y - image_startPoint.Y);if (w > 10 && h > 10){roi = new Rect(image_startPoint.X, image_startPoint.Y, w, h);//Console.WriteLine(String.Format("ROI:({0},{1})-({2},{3})", image_startPoint.X, image_startPoint.Y, image_endPoint.X, image_endPoint.Y));//test//OpenCvSharp.Point pointinfo = new OpenCvSharp.Point(910, 641);//roi = new Rect(pointinfo.X - 160, pointinfo.Y - 430, 380, 940);Mat roi_mat = image[roi];pictureBox2.Image = BitmapConverter.ToBitmap(roi_mat);}//pictureBox1.Invalidate();}private void pictureBox1_MouseDown(object sender, MouseEventArgs e){if (pictureBox1.Image == null)return;m_mouseDown = true;startPoint = e.Location;}private System.Drawing.Point ConvertCooridinate(System.Drawing.Point point){System.Reflection.PropertyInfo rectangleProperty = this.pictureBox1.GetType().GetProperty("ImageRectangle", BindingFlags.Instance | BindingFlags.NonPublic);Rectangle pictureBox = (Rectangle)rectangleProperty.GetValue(this.pictureBox1, null);int zoomedWidth = pictureBox.Width;int zoomedHeight = pictureBox.Height;int imageWidth = pictureBox1.Image.Width;int imageHeight = pictureBox1.Image.Height;double zoomRatex = (double)(zoomedWidth) / (double)(imageWidth);double zoomRatey = (double)(zoomedHeight) / (double)(imageHeight);int black_left_width = (zoomedWidth == this.pictureBox1.Width) ? 0 : (this.pictureBox1.Width - zoomedWidth) / 2;int black_top_height = (zoomedHeight == this.pictureBox1.Height) ? 0 : (this.pictureBox1.Height - zoomedHeight) / 2;int zoomedX = point.X - black_left_width;int zoomedY = point.Y - black_top_height;System.Drawing.Point outPoint = new System.Drawing.Point();outPoint.X = (int)((double)zoomedX / zoomRatex);outPoint.Y = (int)((double)zoomedY / zoomRatey);return outPoint;}}
}

下载

源码下载


 

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

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

相关文章

使用Javassist 在android运行时生成类

序言 最近在写框架&#xff0c;有一个需求就是动态的生成一个类&#xff0c;然后查阅了相关文献&#xff0c;发现在android中动态生成一个类还挺麻烦。因次把一些内容分享出来&#xff0c;帮助大家少走弯路。 方案一 DexMaker DexMaker 是一个针对 Android 平台的库&#xf…

“女神节倒计时”给你心爱的她准备惊喜了吗?别着急,闪侠惠递来帮你!

女神节马上就要到了&#xff0c;你给亲爱的她准备惊喜了吗&#xff1f;如果没有&#xff0c;别着急&#xff0c;还有时间可以用心准备准备&#xff0c;如果准备了&#xff0c;你打算怎么送给她呢&#xff1f;当面送给她&#xff1f;快递邮寄给她&#xff1f;可是快递费好昂贵的…

STM32利用标准库编写中断控制oled计数(proteus仿真)

先看先程序效果&#xff1a;每按动一次按钮OLED显示的值加1.这个按键的检测是用中断完成的。 这个工程是在上一个工程&#xff1a;的基础上来完成的&#xff0c;主要是在Mycode文件夹里面新建了两个文件来创建中断的功能方式如下&#xff1a;结构很简单&#xff0c;就是count.c…

【JavaScript】面试手撕浅拷贝

【JavaScript】面试手撕浅拷贝 引入 浅拷贝和深拷贝应该是面试时非常常见的问题了&#xff0c;为了能将这两者说清楚&#xff0c;于是打算用两篇文章分别解释下深浅拷贝。 PS: 我第一次听到拷贝这个词&#xff0c;有种莫名的熟悉感&#xff0c;感觉跟某个英文很相似&#xff…

工业云组态:制造业数字化转型的关键

随着第四次工业革命的到来&#xff0c;数字化转型已成为制造业提升竞争力、实现可持续发展的核心驱动力。在这一背景下&#xff0c;HiWoo Cloud平台推出了工业云组态解决方案&#xff0c;旨在通过云计算、大数据和物联网等先进技术的融合&#xff0c;助力制造业实现智能化、高效…

力扣经典题目解析--最小覆盖子串

原题地址: . - 力扣&#xff08;LeetCode&#xff09; 给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串&#xff0c;则返回空字符串 "" 。 注意&#xff1a; 对于 t 中重复字符&#xff0c;我们寻找…

刷题日记:面试经典 150 题 DAY3

刷题日记&#xff1a;面试经典 150 题 DAY3 274. H 指数238. 除自身以外数组的乘积380. O(1) 时间插入、删除和获取随机元素134. 加油站135. 分发糖果 274. H 指数 原题链接 274. H 指数 重要的是都明白H指数到底是是个啥。注意到如果将引用数从大到小排序&#xff0c;则对于…

考研复试指南

1. 记住&#xff0c;复试的本质不是考试&#xff0c;而是一场自我展示。 考研复试并非简单的知识考察&#xff0c;更是一场展示自我能力和潜力的机会。除了学科知识&#xff0c;考官更关注你的综合素质、学术兴趣和未来发展规划。因此&#xff0c;要保持自信&#xff0c;用更全…

机器学习模型总结

多元线性回归&#xff08;linear regression&#xff09; 自变量&#xff1a;连续型数据&#xff0c;因变量&#xff1a;连续型数据 选自&#xff1a;周志华老师《机器学习》P53-55 思想&#xff1a;残差平方和达到最小时的关系式子即为所求&#xff0c;残差平方和&#xff1a…

uniapp 部署h5,pdf预览

1.hubuilderx 打包h5。 2.上传部署包到服务器。 解压部署包&#xff1a;unzip h5.zip 。 3.nginx配置。 user root; worker_processes 1; #worker_cpu_affinity 0001 0010 0100 1000; #error_log logs/error.log; #error_log logs/error.log notice; error_log /var/l…

抖店怎么入驻?具体的入驻流程是什么?新手一看就会!

我是电商珠珠 新的一年开始了&#xff0c;又有不少新手小伙伴入驻了抖店。我做电商已经五年了&#xff0c;做抖店做了三年多&#xff0c;期间带着学员一起做店。所以对于他们所犯的这些操作错误&#xff0c;相信部分新手小伙伴也会犯错&#xff0c;为了让大家少走点弯路&#…

便携式气象站的工作原理

TH-BQX8便携式气象站是一种轻便、易于携带的气象监测设备&#xff0c;它能够快速部署在需要监测的区域&#xff0c;实时监测和记录气象环境数据。与全自动气象监测站相比&#xff0c;便携式气象站更加注重移动性和灵活性&#xff0c;适用于临时性的气象监测任务或特定区域的气象…