【转载】魔幻的C# Onnx技术:一键抠图,分割万物,让你的图片变得更有魔力!

效果

效果

原项目

1
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.

模型信息

sam_vit_b_decoder.onnx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Model Properties
-------------------------
---------------------------------------------------------------

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

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

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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();

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

}
}

From 公众号:天天代码码天天


【转载】魔幻的C# Onnx技术:一键抠图,分割万物,让你的图片变得更有魔力!
https://bgmh.work/2024/04/20/魔幻的CSharp-Onnx技术:一键抠图,分割万物,让你的图片变得更有魔力!/
作者
OuHuanHua
发布于
2024年4月20日
许可协议