-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMainForm.cs
More file actions
395 lines (328 loc) · 15 KB
/
MainForm.cs
File metadata and controls
395 lines (328 loc) · 15 KB
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
using System.Diagnostics;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
namespace Backsolate
{
public partial class MainForm : Form
{
private Bitmap originalImage;
private Bitmap? processedImage;
static string modelUrl = "https://github.com/danielgatis/rembg/releases/download/v0.0.0/u2net.onnx";
string modelPath = Path.Combine(Application.StartupPath, Path.GetFileName(modelUrl));
string selectedModel = "u2net";
string originalFileName = "picture";
string imageInfo = "No image is loaded. Load an image to view its resolution and filesize here...";
public MainForm()
{
InitializeComponent();
originalImage = new Bitmap(pictureBoxOriginal.Width, pictureBoxOriginal.Height);
processedImage = null;
foreach (var model in ModelCatalog.Models)
{
modelSelect.DropDown.Items.Add(model.Key);
}
}
private async Task DownloadModelAsync(string url, string destinationPath)
{
progressBar.Value = 0;
if (!File.Exists(modelPath))
{
using (HttpClient client = new HttpClient())
{
lblInfoText.Text = "Downloading model...";
using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
{
response.EnsureSuccessStatusCode();
long totalBytes = response.Content.Headers.ContentLength ?? -1;
long receivedBytes = 0;
using (var fs = new FileStream(destinationPath, FileMode.Create, FileAccess.Write, FileShare.None))
using (var stream = await response.Content.ReadAsStreamAsync())
{
byte[] buffer = new byte[8192];
int bytesRead;
DateTime startTime = DateTime.Now;
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await fs.WriteAsync(buffer, 0, bytesRead);
receivedBytes += bytesRead;
TimeSpan elapsedTime = DateTime.Now - startTime;
if (totalBytes > 0)
{
int progressPercentage = (int)(receivedBytes * 100 / totalBytes);
progressBar.Value = progressPercentage;
double speed = receivedBytes / elapsedTime.TotalSeconds;
lblInfoText.Text = $"Downloading model... ({FormatFileSize(receivedBytes)}/{FormatFileSize(totalBytes)}) [{progressPercentage}%] Speed: {FormatFileSize((long)speed)}/s";
Update();
}
}
}
}
lblInfoText.Text = "Model downloaded successfully!";
progressBar.Value = 100;
}
}
}
private async void btnRemoveBackground_Click(object sender, EventArgs e)
{
if (originalImage == null)
{
MessageBox.Show("Please load an image first.");
return;
}
try
{
btnRemoveBackground.Enabled = false;
modelSelect.Enabled = false;
modelPath = Path.Combine(Application.StartupPath, Path.GetFileName(modelUrl));
await DownloadModelAsync(modelUrl, modelPath);
Stopwatch stopwatch = Stopwatch.StartNew();
progressBar.Value = 0;
processedImage = await RemoveBackgroundAsync(originalImage);
pictureBoxProcessed.Image = processedImage;
stopwatch.Stop();
TimeSpan elapsedTime = stopwatch.Elapsed;
string elapsedTimeString = string.Format("{0:00}:{1:00}:{2:00}.{3:00}",
elapsedTime.Hours, elapsedTime.Minutes, elapsedTime.Seconds, elapsedTime.Milliseconds / 10);
ShowUpdate($"Done. (Took {elapsedTimeString})", 20);
}
catch (Exception ex)
{
MessageBox.Show($"An error occurred: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
progressBar.Value = 0;
}
finally
{
btnRemoveBackground.Enabled = true;
modelSelect.Enabled = true;
}
}
private void ShowUpdate(string msg, int pbIncrement)
{
lblInfoText.Text = msg;
progressBar.Value += pbIncrement;
Update();
}
private async void RedownloadModelAsk()
{
var result = MessageBox.Show(
"Would you like to redownload the model? The current model file may be corrupt.",
"Unexpected Error", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
lblInfoText.Text = "Attempting to download the model again...";
try
{
await DownloadModelAsync(modelUrl, modelPath);
lblInfoText.Text = "Model downloaded successfully!";
}
catch (Exception ex)
{
MessageBox.Show($"An error occurred while downloading the model: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private async Task<Bitmap> RemoveBackgroundAsync(Bitmap image)
{
try
{
ShowUpdate($"Preparing model session ({selectedModel})...", 0);
return await Task.Run(() =>
{
using var session = new InferenceSession(modelPath);
var inputName = session.InputMetadata.Keys.FirstOrDefault();
var outputName = session.OutputMetadata.Keys.FirstOrDefault();
if (string.IsNullOrEmpty(inputName) || string.IsNullOrEmpty(outputName))
throw new InvalidOperationException("Model input or output names could not be determined.");
ShowUpdate("Preprocessing image...", 20);
var inputTensor = PreprocessImage(image);
ShowUpdate("Running model...", 20);
var inputs = new List<NamedOnnxValue> { NamedOnnxValue.CreateFromTensor(inputName, inputTensor) };
using IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results = session.Run(inputs);
ShowUpdate("Postprocessing image...", 20);
var mask = PostprocessMask(results.First().AsTensor<float>(), image.Width, image.Height);
ShowUpdate("Applying alpha mask...", 20);
return ApplyMask(image, mask);
});
}
catch (FileNotFoundException)
{
MessageBox.Show("Model file not found. Please check if the model file exists and is in the correct location.",
"Model File Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
RedownloadModelAsk();
progressBar.Value = 0;
}
catch (OnnxRuntimeException ex)
{
MessageBox.Show($"An error occurred while running the ONNX model:\n{ex.Message}",
"Model Execution Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
progressBar.Value = 0;
}
catch (InvalidOperationException ex)
{
MessageBox.Show($"An invalid operation occurred:\n{ex.Message}",
"Invalid Operation", MessageBoxButtons.OK, MessageBoxIcon.Error);
progressBar.Value = 0;
}
catch (Exception ex)
{
MessageBox.Show($"Unexpected error occurred:\n{ex.Message}",
"Unexpected error", MessageBoxButtons.OK, MessageBoxIcon.Error);
progressBar.Value = 0;
}
return image;
}
private DenseTensor<float> PreprocessImage(Bitmap image)
{
int size = ModelCatalog.ModelPreferredSize[selectedModel];
Bitmap resizedImage = new Bitmap(image, new Size(size, size));
DenseTensor<float> tensor = new DenseTensor<float>(new[] { 1, 3, size, size });
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
Color pixel = resizedImage.GetPixel(x, y);
tensor[0, 0, y, x] = pixel.R / 255f;
tensor[0, 1, y, x] = pixel.G / 255f;
tensor[0, 2, y, x] = pixel.B / 255f;
}
}
return tensor;
}
private float[,] PostprocessMask(Tensor<float> mask, int originalWidth, int originalHeight)
{
var maskData = mask.ToArray();
var resizedMask = new float[originalHeight, originalWidth];
float scaleX = (float)mask.Dimensions[3] / originalWidth;
float scaleY = (float)mask.Dimensions[2] / originalHeight;
for (int y = 0; y < originalHeight; y++)
{
for (int x = 0; x < originalWidth; x++)
{
int srcX = (int)(x * scaleX);
int srcY = (int)(y * scaleY);
resizedMask[y, x] = maskData[srcY * mask.Dimensions[3] + srcX];
}
}
return resizedMask;
}
private Bitmap ApplyMask(Bitmap image, float[,] mask)
{
Bitmap result = new Bitmap(image.Width, image.Height);
for (int y = 0; y < image.Height; y++)
{
for (int x = 0; x < image.Width; x++)
{
Color pixel = image.GetPixel(x, y);
float alpha = mask[y, x];
result.SetPixel(x, y, Color.FromArgb((int)(alpha * 255), pixel.R, pixel.G, pixel.B));
}
}
return result;
}
private void OpenImageFile()
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "Image Files|*.jpg;*.jpeg;*.png";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
originalFileName = Path.GetFileNameWithoutExtension(openFileDialog.FileName);
originalImage = new Bitmap(openFileDialog.FileName);
pictureBoxOriginal.Image = originalImage;
FileInfo fileInfo = new FileInfo(openFileDialog.FileName);
imageInfo = $"Input Resolution: {originalImage.Size.Width}x{originalImage.Size.Height}\nInput File Size: {FormatFileSize(fileInfo.Length)}";
}
}
}
private void SaveImageFile()
{
if (processedImage == null)
{
MessageBox.Show("No processed image to save. To remove background from an image, please click on the box above the label 'Original Image'.", "Can't save resultant image", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "PNG Image|*.png";
saveFileDialog.FileName = $"{originalFileName}-removed-bg.png";
saveFileDialog.Title = "Save image as...";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
processedImage.Save(saveFileDialog.FileName);
}
}
}
private void pictureBoxOriginal_Click(object sender, EventArgs e)
{
OpenImageFile();
}
private string FormatFileSize(long bytes)
{
const long kb = 1024;
const long mb = kb * 1024;
const long gb = mb * 1024;
if (bytes >= gb)
{
return $"{(double)bytes / gb:F2} GB";
}
else if (bytes >= mb)
{
return $"{(double)bytes / mb:F2} MB";
}
else if (bytes >= kb)
{
return $"{(double)bytes / kb:F2} KB";
}
else
{
return $"{bytes} bytes";
}
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutForm aboutForm = new AboutForm();
aboutForm.ShowDialog();
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
originalImage = new Bitmap(pictureBoxOriginal.Width, pictureBoxOriginal.Height);
processedImage = new Bitmap(pictureBoxProcessed.Width, pictureBoxProcessed.Height);
pictureBoxOriginal.Image = originalImage;
pictureBoxProcessed.Image = processedImage;
imageInfo = "No image is loaded. Load an image to view its resolution and filesize here...";
}
private void customizeToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show(imageInfo, "Input Image Information");
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveImageFile();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenImageFile();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void pictureBoxProcessed_Click(object sender, EventArgs e)
{
SaveImageFile();
}
private void modelSelect_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
try
{
modelSelect.Text = e.ClickedItem?.Text;
selectedModel = e.ClickedItem.Text ?? "u2net";
modelUrl = ModelCatalog.Models[selectedModel];
}
catch (NullReferenceException ex)
{
lblInfoText.Text = "Unable to select model: " + ex.Message;
}
}
}
}