forked from dotnet/machinelearning-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainWindow.xaml.cs
201 lines (167 loc) · 7.44 KB
/
MainWindow.xaml.cs
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
using Microsoft.ML;
using OnnxObjectDetection;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Rectangle = System.Windows.Shapes.Rectangle;
namespace OnnxObjectDetectionApp
{
public partial class MainWindow : System.Windows.Window
{
private VideoCapture capture;
private CancellationTokenSource cameraCaptureCancellationTokenSource;
private OnnxOutputParser outputParser;
private PredictionEngine<ImageInputData, TinyYoloPrediction> tinyYoloPredictionEngine;
private PredictionEngine<ImageInputData, CustomVisionPrediction> customVisionPredictionEngine;
private static readonly string modelsDirectory = Path.Combine(Environment.CurrentDirectory, @"ML\OnnxModels");
public MainWindow()
{
InitializeComponent();
LoadModel();
}
protected override void OnActivated(EventArgs e)
{
base.OnActivated(e);
StartCameraCapture();
}
protected override void OnDeactivated(EventArgs e)
{
base.OnDeactivated(e);
StopCameraCapture();
}
private void LoadModel()
{
// Check for an Onnx model exported from Custom Vision
var customVisionExport = Directory.GetFiles(modelsDirectory, "*.zip").FirstOrDefault();
// If there is one, use it.
if (customVisionExport != null)
{
var customVisionModel = new CustomVisionModel(customVisionExport);
var modelConfigurator = new OnnxModelConfigurator(customVisionModel);
outputParser = new OnnxOutputParser(customVisionModel);
customVisionPredictionEngine = modelConfigurator.GetMlNetPredictionEngine<CustomVisionPrediction>();
}
else // Otherwise default to Tiny Yolo Onnx model
{
var tinyYoloModel = new TinyYoloModel(Path.Combine(modelsDirectory, "TinyYolo2_model.onnx"));
var modelConfigurator = new OnnxModelConfigurator(tinyYoloModel);
outputParser = new OnnxOutputParser(tinyYoloModel);
tinyYoloPredictionEngine = modelConfigurator.GetMlNetPredictionEngine<TinyYoloPrediction>();
}
}
private void StartCameraCapture()
{
cameraCaptureCancellationTokenSource = new CancellationTokenSource();
Task.Run(() => CaptureCamera(cameraCaptureCancellationTokenSource.Token), cameraCaptureCancellationTokenSource.Token) ;
}
private void StopCameraCapture() => cameraCaptureCancellationTokenSource?.Cancel();
private async Task CaptureCamera(CancellationToken token)
{
if (capture == null)
capture = new VideoCapture(CaptureDevice.DShow);
capture.Open(0);
if (capture.IsOpened())
{
while (!token.IsCancellationRequested)
{
using MemoryStream memoryStream = capture.RetrieveMat().Flip(FlipMode.Y).ToMemoryStream();
await Application.Current.Dispatcher.InvokeAsync(() =>
{
var imageSource = new BitmapImage();
imageSource.BeginInit();
imageSource.CacheOption = BitmapCacheOption.OnLoad;
imageSource.StreamSource = memoryStream;
imageSource.EndInit();
WebCamImage.Source = imageSource;
});
var bitmapImage = new Bitmap(memoryStream);
await ParseWebCamFrame(bitmapImage, token);
}
capture.Release();
}
}
async Task ParseWebCamFrame(Bitmap bitmap, CancellationToken token)
{
if (customVisionPredictionEngine == null && tinyYoloPredictionEngine == null)
return;
var frame = new ImageInputData { Image = bitmap };
var filteredBoxes = DetectObjectsUsingModel(frame);
if (!token.IsCancellationRequested)
{
await Application.Current.Dispatcher.InvokeAsync(() =>
{
DrawOverlays(filteredBoxes, WebCamImage.ActualHeight, WebCamImage.ActualWidth);
});
}
}
public List<BoundingBox> DetectObjectsUsingModel(ImageInputData imageInputData)
{
var labels = customVisionPredictionEngine?.Predict(imageInputData).PredictedLabels ?? tinyYoloPredictionEngine?.Predict(imageInputData).PredictedLabels;
var boundingBoxes = outputParser.ParseOutputs(labels);
var filteredBoxes = outputParser.FilterBoundingBoxes(boundingBoxes, 5, 0.5f);
return filteredBoxes;
}
private void DrawOverlays(List<BoundingBox> filteredBoxes, double originalHeight, double originalWidth)
{
WebCamCanvas.Children.Clear();
foreach (var box in filteredBoxes)
{
// process output boxes
double x = Math.Max(box.Dimensions.X, 0);
double y = Math.Max(box.Dimensions.Y, 0);
double width = Math.Min(originalWidth - x, box.Dimensions.Width);
double height = Math.Min(originalHeight - y, box.Dimensions.Height);
// fit to current image size
x = originalWidth * x / ImageSettings.imageWidth;
y = originalHeight * y / ImageSettings.imageHeight;
width = originalWidth * width / ImageSettings.imageWidth;
height = originalHeight * height / ImageSettings.imageHeight;
var boxColor = box.BoxColor.ToMediaColor();
var objBox = new Rectangle
{
Width = width,
Height = height,
Fill = new SolidColorBrush(Colors.Transparent),
Stroke = new SolidColorBrush(boxColor),
StrokeThickness = 2.0,
Margin = new Thickness(x, y, 0, 0)
};
var objDescription = new TextBlock
{
Margin = new Thickness(x + 4, y + 4, 0, 0),
Text = box.Description,
FontWeight = FontWeights.Bold,
Width = 126,
Height = 21,
TextAlignment = TextAlignment.Center
};
var objDescriptionBackground = new Rectangle
{
Width = 134,
Height = 29,
Fill = new SolidColorBrush(boxColor),
Margin = new Thickness(x, y, 0, 0)
};
WebCamCanvas.Children.Add(objDescriptionBackground);
WebCamCanvas.Children.Add(objDescription);
WebCamCanvas.Children.Add(objBox);
}
}
}
internal static class ColorExtensions
{
internal static System.Windows.Media.Color ToMediaColor(this System.Drawing.Color drawingColor)
{
return System.Windows.Media.Color.FromArgb(drawingColor.A, drawingColor.R, drawingColor.G, drawingColor.B);
}
}
}