-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
397 lines (334 loc) · 16.6 KB
/
MainWindow.xaml.cs
File metadata and controls
397 lines (334 loc) · 16.6 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
396
397
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.ProjectOxford.Common.Contract;
using Microsoft.ProjectOxford.Face;
using Microsoft.ProjectOxford.Face.Contract;
namespace FaceID
{
public partial class MainWindow : Window
{
// Replace the first parameter with your valid subscription key.
//
// Replace or verify the region in the second parameter.
//
// You must use the same region in your REST API call as you used to obtain your subscription keys.
// For example, if you obtained your subscription keys from the westus region, replace
// "westcentralus" in the URI below with "westus".
//
// NOTE: Free trial subscription keys are generated in the westcentralus region, so if you are using
// a free trial subscription key, you should not need to change this region.
private readonly IFaceServiceClient faceServiceClient = new FaceServiceClient("1b2b34b4e1d441ccb4b43923f9c8cc9d", "https://westcentralus.api.cognitive.microsoft.com/face/v1.0");
private const string subscriptionKey = "1b2b34b4e1d441ccb4b43923f9c8cc9d";
private const string FACEIDUri = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect";
Face[] faces; // The list of detected faces.
String[] faceDescriptions; // The list of descriptions for the detected faces.
Face[] faces1;
String[] faceDescriptions1;
double resizeFactor; // The resize factor for the displayed image.
double resizeFactor1;
public MainWindow()
{
InitializeComponent();
}
#region buton click
// Displays the image and calls Detect Faces. for button 1
private async void BrowseButton_Click(object sender, RoutedEventArgs e)
{
// Get the image file to scan from the user.
var openDlg = new Microsoft.Win32.OpenFileDialog();
openDlg.Filter = "JPEG Image(*.jpg)|*.jpg";
bool? result = openDlg.ShowDialog(this);
// Return if canceled.
if (!(bool)result)
{
return;
}
// Display the image file.
string filePath = openDlg.FileName;
Uri fileUri = new Uri(filePath);
BitmapImage bitmapSource = new BitmapImage();
bitmapSource.BeginInit();
bitmapSource.CacheOption = BitmapCacheOption.None;
bitmapSource.UriSource = fileUri;
bitmapSource.EndInit();
FacePhoto.Source = bitmapSource;
// Detect any faces in the image.
Title = "Detecting...";
faces = await UploadAndDetectFaces(filePath);
Title = String.Format("Detection Finished. {0} face(s) detected", faces.Length);
if (faces.Length > 0)
{
// Prepare to draw rectangles around the faces.
DrawingVisual visual = new DrawingVisual();
DrawingContext drawingContext = visual.RenderOpen();
drawingContext.DrawImage(bitmapSource, new Rect(0, 0, bitmapSource.Width, bitmapSource.Height));
double dpi = bitmapSource.DpiX;
resizeFactor = 96 / dpi;
faceDescriptions = new String[faces.Length];
for (int i = 0; i < faces.Length; ++i)
{
Face face = faces[i];
// Draw a rectangle on the face.
drawingContext.DrawRectangle(
Brushes.Transparent,
new Pen(Brushes.Red, 2),
new Rect(
face.FaceRectangle.Left * resizeFactor,
face.FaceRectangle.Top * resizeFactor,
face.FaceRectangle.Width * resizeFactor,
face.FaceRectangle.Height * resizeFactor
)
);
// Store the face description.
faceDescriptions[i] = FaceDescription(face);
}
drawingContext.Close();
// Display the image with the rectangle around the face.
RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(
(int)(bitmapSource.PixelWidth * resizeFactor),
(int)(bitmapSource.PixelHeight * resizeFactor),
96,
96,
PixelFormats.Pbgra32);
faceWithRectBitmap.Render(visual);
FacePhoto.Source = faceWithRectBitmap;
// Set the status bar text.
faceDescriptionStatusBar.Text = "Place the mouse pointer over a face to see the face description.";
}
}
//for button2
private async void BrowseButton_Click1(object sender, RoutedEventArgs e)
{
// Get the image file to scan from the user.
var openDlg = new Microsoft.Win32.OpenFileDialog();
openDlg.Filter = "JPEG Image(*.jpg)|*.jpg";
bool? result = openDlg.ShowDialog(this);
// Return if canceled.
if (!(bool)result)
{
return;
}
// Display the image file.
string filePath = openDlg.FileName;
Uri fileUri = new Uri(filePath);
BitmapImage bitmapSource = new BitmapImage();
bitmapSource.BeginInit();
bitmapSource.CacheOption = BitmapCacheOption.None;
bitmapSource.UriSource = fileUri;
bitmapSource.EndInit();
FacePhoto1.Source = bitmapSource;
// Detect any faces in the image.
Title = "Detecting...";
faces1 = await UploadAndDetectFaces(filePath);
Title = String.Format("Detection Finished. {0} face(s) detected", faces1.Length);
if (faces1.Length > 0)
{
// Prepare to draw rectangles around the faces.
DrawingVisual visual = new DrawingVisual();
DrawingContext drawingContext = visual.RenderOpen();
drawingContext.DrawImage(bitmapSource, new Rect(0, 0, bitmapSource.Width, bitmapSource.Height));
double dpi = bitmapSource.DpiX;
resizeFactor1 = 96 / dpi;
faceDescriptions1 = new String[faces1.Length];
for (int i = 0; i < faces1.Length; ++i)
{
Face face = faces1[i];
// Draw a rectangle on the face.
drawingContext.DrawRectangle(
Brushes.Transparent,
new Pen(Brushes.Red, 2),
new Rect(
face.FaceRectangle.Left * resizeFactor1,
face.FaceRectangle.Top * resizeFactor1,
face.FaceRectangle.Width * resizeFactor1,
face.FaceRectangle.Height * resizeFactor1
)
);
// Store the face description.
faceDescriptions1[i] = FaceDescription(face);
}
drawingContext.Close();
// Display the image with the rectangle around the face.
RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(
(int)(bitmapSource.PixelWidth * resizeFactor1),
(int)(bitmapSource.PixelHeight * resizeFactor1),
96,
96,
PixelFormats.Pbgra32);
faceWithRectBitmap.Render(visual);
FacePhoto1.Source = faceWithRectBitmap;
faceDescriptionStatusBar1.Text = faceDescriptions1[0];
// Set the status bar text.
//faceDescriptionStatusBar1.Text = "Place the mouse pointer over a face to see the face description.";
}
}
//for check button
private async void CheckSimilar_Click(object sender, RoutedEventArgs e)
{
if(faces == null || faces1 == null)
{
isSameFace.Text = "Upload two faces first...";
return;
}
var verifyResult = await faceServiceClient.VerifyAsync(faces[0].FaceId, faces1[0].FaceId);
bool isSame = verifyResult.IsIdentical;
double confidence = verifyResult.Confidence;
if (isSame)
{
isSameFace.Text = string.Format("They are same person , similar percentage:{0}", confidence);
}
else
{
isSameFace.Text = string.Format("They are not same person, similar percentage:{0}", confidence);
}
}
#endregion
// Displays the face description when the mouse is over a face rectangle.
private void FacePhoto_MouseMove(object sender, MouseEventArgs e)
{
// If the REST call has not completed, return from this method.
if (faces == null)
return;
// Find the mouse position relative to the image.
Point mouseXY = e.GetPosition(FacePhoto);
ImageSource imageSource = FacePhoto.Source;
BitmapSource bitmapSource = (BitmapSource)imageSource;
// Scale adjustment between the actual size and displayed size.
var scale = FacePhoto.ActualWidth / (bitmapSource.PixelWidth / resizeFactor);
// Check if this mouse position is over a face rectangle.
bool mouseOverFace = false;
for (int i = 0; i < faces.Length; ++i)
{
FaceRectangle fr = faces[i].FaceRectangle;
double left = fr.Left * scale;
double top = fr.Top * scale;
double width = fr.Width * scale;
double height = fr.Height * scale;
// Display the face description for this face if the mouse is over this face rectangle.
if (mouseXY.X >= left && mouseXY.X <= left + width && mouseXY.Y >= top && mouseXY.Y <= top + height)
{
faceDescriptionStatusBar.Text = faceDescriptions[i];
mouseOverFace = true;
break;
}
}
// If the mouse is not over a face rectangle.
if (!mouseOverFace)
{
faceDescriptionStatusBar.Text = "Place the mouse pointer over a face to see the face description.";
}
}
//Not use it for now
private void FacePhoto_MouseMove1(object sender, MouseEventArgs e)
{
// If the REST call has not completed, return from this method.
if (faces1 == null)
return;
// Find the mouse position relative to the image.
Point mouseXY = e.GetPosition(FacePhoto1);
ImageSource imageSource = FacePhoto1.Source;
BitmapSource bitmapSource = (BitmapSource)imageSource;
// Scale adjustment between the actual size and displayed size.
var scale = FacePhoto1.ActualWidth / (bitmapSource.PixelWidth / resizeFactor);
// Check if this mouse position is over a face rectangle.
bool mouseOverFace = false;
for (int i = 0; i < faces1.Length; ++i)
{
FaceRectangle fr = faces1[i].FaceRectangle;
double left = fr.Left * scale;
double top = fr.Top * scale;
double width = fr.Width * scale;
double height = fr.Height * scale;
// Display the face description for this face if the mouse is over this face rectangle.
if (mouseXY.X >= left && mouseXY.X <= left + width && mouseXY.Y >= top && mouseXY.Y <= top + height)
{
faceDescriptionStatusBar1.Text = faceDescriptions1[i];
mouseOverFace = true;
break;
}
}
// If the mouse is not over a face rectangle.
if (!mouseOverFace)
{
faceDescriptionStatusBar1.Text = "Place the mouse pointer over a face to see the face description.";
}
}
// Uploads the image file and calls Detect Faces.
private async Task<Face[]> UploadAndDetectFaces(string imageFilePath)
{
// The list of Face attributes to return.
IEnumerable<FaceAttributeType> faceAttributes = new FaceAttributeType[] { FaceAttributeType.Gender, FaceAttributeType.Age, FaceAttributeType.Smile, FaceAttributeType.Emotion, FaceAttributeType.Glasses, FaceAttributeType.Hair };
// Call the Face API.
try
{
using (Stream imageFileStream = File.OpenRead(imageFilePath))
{
Face[] faces = await faceServiceClient.DetectAsync(imageFileStream, returnFaceId: true, returnFaceLandmarks: false, returnFaceAttributes: faceAttributes);
return faces;
}
}
// Catch and display Face API errors.
catch (FaceAPIException f)
{
MessageBox.Show(f.ErrorMessage, f.ErrorCode);
return new Face[0];
}
// Catch and display all other errors.
catch (Exception e)
{
MessageBox.Show(e.Message, "Error");
return new Face[0];
}
}
// Returns a string that describes the given face.
private string FaceDescription(Face face)
{
StringBuilder sb = new StringBuilder();
sb.Append("Face: ");
// Add the gender, age, and smile.
sb.Append(face.FaceAttributes.Gender);
sb.Append(", ");
sb.Append(face.FaceAttributes.Age);
sb.Append(", ");
sb.Append(String.Format("smile {0:F1}%, ", face.FaceAttributes.Smile * 100));
// Add the emotions. Display all emotions over 10%.
sb.Append("Emotion: ");
EmotionScores emotionScores = face.FaceAttributes.Emotion;
if (emotionScores.Anger >= 0.1f) sb.Append(String.Format("anger {0:F1}%, ", emotionScores.Anger * 100));
if (emotionScores.Contempt >= 0.1f) sb.Append(String.Format("contempt {0:F1}%, ", emotionScores.Contempt * 100));
if (emotionScores.Disgust >= 0.1f) sb.Append(String.Format("disgust {0:F1}%, ", emotionScores.Disgust * 100));
if (emotionScores.Fear >= 0.1f) sb.Append(String.Format("fear {0:F1}%, ", emotionScores.Fear * 100));
if (emotionScores.Happiness >= 0.1f) sb.Append(String.Format("happiness {0:F1}%, ", emotionScores.Happiness * 100));
if (emotionScores.Neutral >= 0.1f) sb.Append(String.Format("neutral {0:F1}%, ", emotionScores.Neutral * 100));
if (emotionScores.Sadness >= 0.1f) sb.Append(String.Format("sadness {0:F1}%, ", emotionScores.Sadness * 100));
if (emotionScores.Surprise >= 0.1f) sb.Append(String.Format("surprise {0:F1}%, ", emotionScores.Surprise * 100));
// Add glasses.
sb.Append(face.FaceAttributes.Glasses);
sb.Append(", ");
// Add hair.
sb.Append("Hair: ");
// Display baldness confidence if over 1%.
if (face.FaceAttributes.Hair.Bald >= 0.01f)
sb.Append(String.Format("bald {0:F1}% ", face.FaceAttributes.Hair.Bald * 100));
// Display all hair color attributes over 10%.
HairColor[] hairColors = face.FaceAttributes.Hair.HairColor;
foreach (HairColor hairColor in hairColors)
{
if (hairColor.Confidence >= 0.1f)
{
sb.Append(hairColor.Color.ToString());
sb.Append(String.Format(" {0:F1}% ", hairColor.Confidence * 100));
}
}
// Return the built string.
return sb.ToString();
}
}
}