forked from microsoft/Cognitive-Samples-IntelligentKiosk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImageWithFaceBorderUserControl.xaml.cs
694 lines (598 loc) · 30.4 KB
/
ImageWithFaceBorderUserControl.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
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Cognitive Services: http://www.microsoft.com/cognitive
//
// Microsoft Cognitive Services Github:
// https://github.com/Microsoft/Cognitive
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
using Microsoft.Azure.CognitiveServices.Vision.Face.Models;
using ServiceHelpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
namespace IntelligentKioskSample.Controls
{
public class EmotionFeedback
{
public string Text { get; set; }
public SolidColorBrush AccentColor { get; set; }
public string ImageFileName { get; set; }
}
public sealed partial class ImageWithFaceBorderUserControl : UserControl
{
private ImageAnalyzer currentImage;
public ImageWithFaceBorderUserControl()
{
this.InitializeComponent();
}
public static readonly DependencyProperty DetectFacesOnLoadProperty =
DependencyProperty.Register(
"DetectFacesOnLoad",
typeof(bool),
typeof(ImageWithFaceBorderUserControl),
new PropertyMetadata(false)
);
public static readonly DependencyProperty ShowMultipleFacesProperty =
DependencyProperty.Register(
"ShowMultipleFaces",
typeof(bool),
typeof(ImageWithFaceBorderUserControl),
new PropertyMetadata(false)
);
public static readonly DependencyProperty PerformRecognitionProperty =
DependencyProperty.Register(
"PerformRecognition",
typeof(bool),
typeof(ImageWithFaceBorderUserControl),
new PropertyMetadata(false)
);
public static readonly DependencyProperty DetectFaceAttributesProperty =
DependencyProperty.Register(
"DetectFaceAttributes",
typeof(bool),
typeof(ImageWithFaceBorderUserControl),
new PropertyMetadata(false)
);
public static readonly DependencyProperty ShowRecognitionResultsProperty =
DependencyProperty.Register(
"ShowRecognitionResults",
typeof(bool),
typeof(ImageWithFaceBorderUserControl),
new PropertyMetadata(false)
);
public static readonly DependencyProperty ShowDialogOnApiErrorsProperty =
DependencyProperty.Register(
"ShowDialogOnApiErrors",
typeof(bool),
typeof(ImageWithFaceBorderUserControl),
new PropertyMetadata(false)
);
public static readonly DependencyProperty ShowEmotionRecognitionProperty =
DependencyProperty.Register(
"ShowEmotionRecognition",
typeof(bool),
typeof(ImageWithFaceBorderUserControl),
new PropertyMetadata(false)
);
public static readonly DependencyProperty BalloonBackgroundProperty =
DependencyProperty.Register(
"BalloonBackground",
typeof(SolidColorBrush),
typeof(ImageWithFaceBorderUserControl),
new PropertyMetadata(null)
);
public static readonly DependencyProperty BalloonForegroundProperty =
DependencyProperty.Register(
"BalloonForeground",
typeof(SolidColorBrush),
typeof(ImageWithFaceBorderUserControl),
new PropertyMetadata(null)
);
public static readonly DependencyProperty DetectFaceLandmarksProperty =
DependencyProperty.Register(
"DetectFaceLandmarks",
typeof(bool),
typeof(ImageWithFaceBorderUserControl),
new PropertyMetadata(false)
);
public static readonly DependencyProperty ShowFaceLandmarksProperty =
DependencyProperty.Register(
"ShowFaceLandmarks",
typeof(bool),
typeof(ImageWithFaceBorderUserControl),
new PropertyMetadata(false)
);
public static readonly DependencyProperty PerformComputerVisionAnalysisProperty =
DependencyProperty.Register(
"PerformComputerVisionAnalysis",
typeof(bool),
typeof(ImageWithFaceBorderUserControl),
new PropertyMetadata(false)
);
public static readonly DependencyProperty PerformOCRAnalysisProperty =
DependencyProperty.Register(
"PerformOCRAnalysis",
typeof(bool),
typeof(ImageWithFaceBorderUserControl),
new PropertyMetadata(false)
);
public static readonly DependencyProperty PerformObjectDetectionProperty =
DependencyProperty.Register(
"PerformObjectDetection",
typeof(bool),
typeof(ImageWithFaceBorderUserControl),
new PropertyMetadata(false)
);
public SolidColorBrush BalloonBackground
{
get { return (SolidColorBrush)GetValue(BalloonBackgroundProperty); }
set { SetValue(BalloonBackgroundProperty, (SolidColorBrush)value); }
}
public SolidColorBrush BalloonForeground
{
get { return (SolidColorBrush)GetValue(BalloonForegroundProperty); }
set { SetValue(BalloonForegroundProperty, (SolidColorBrush)value); }
}
public bool ShowEmotionRecognition
{
get { return (bool)GetValue(ShowEmotionRecognitionProperty); }
set { SetValue(ShowEmotionRecognitionProperty, (bool)value); }
}
public bool ShowMultipleFaces
{
get { return (bool)GetValue(ShowMultipleFacesProperty); }
set { SetValue(ShowMultipleFacesProperty, (bool)value); }
}
public bool DetectFacesOnLoad
{
get { return (bool)GetValue(DetectFacesOnLoadProperty); }
set { SetValue(DetectFacesOnLoadProperty, (bool)value); }
}
public bool DetectFaceAttributes
{
get { return (bool)GetValue(DetectFaceAttributesProperty); }
set { SetValue(DetectFaceAttributesProperty, (bool)value); }
}
public bool PerformRecognition
{
get { return (bool)GetValue(PerformRecognitionProperty); }
set { SetValue(PerformRecognitionProperty, (bool)value); }
}
public bool ShowRecognitionResults
{
get { return (bool)GetValue(ShowRecognitionResultsProperty); }
set { SetValue(ShowRecognitionResultsProperty, (bool)value); }
}
public bool ShowDialogOnApiErrors
{
get { return (bool)GetValue(ShowDialogOnApiErrorsProperty); }
set { SetValue(ShowDialogOnApiErrorsProperty, (bool)value); }
}
public bool DetectFaceLandmarks
{
get { return (bool)GetValue(DetectFaceLandmarksProperty); }
set { SetValue(DetectFaceLandmarksProperty, (bool)value); }
}
public bool ShowFaceLandmarks
{
get { return (bool)GetValue(ShowFaceLandmarksProperty); }
set { SetValue(ShowFaceLandmarksProperty, value); }
}
public bool PerformComputerVisionAnalysis
{
get { return (bool)GetValue(PerformComputerVisionAnalysisProperty); }
set { SetValue(PerformComputerVisionAnalysisProperty, (bool)value); }
}
public bool PerformOCRAnalysis
{
get { return (bool)GetValue(PerformOCRAnalysisProperty); }
set { SetValue(PerformOCRAnalysisProperty, (bool)value); }
}
public bool PerformObjectDetection
{
get { return (bool)GetValue(PerformObjectDetectionProperty); }
set { SetValue(PerformObjectDetectionProperty, (bool)value); }
}
public TextRecognitionMode TextRecognitionMode { get; set; }
private async void OnDataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
{
ImageAnalyzer dataContext = this.DataContext as ImageAnalyzer;
if (this.currentImage != dataContext)
{
this.currentImage = dataContext;
}
else
{
// Windows sometimes fires multiple DataContextChanged events.
// If we are here that is one of those cases, and since we already set
// the data context to this value we can ignore it
return;
}
foreach (var child in this.hostGrid.Children.Where(c => !(c is Image)).ToArray())
{
this.hostGrid.Children.Remove(child);
}
// remove the current source
this.bitmapImage.UriSource = null;
if (dataContext != null)
{
try
{
if (dataContext.ImageUrl != null)
{
this.bitmapImage.UriSource = new Uri(dataContext.ImageUrl);
}
else if (dataContext.GetImageStreamCallback != null)
{
await this.bitmapImage.SetSourceAsync((await dataContext.GetImageStreamCallback()).AsRandomAccessStream());
}
}
catch (Exception ex)
{
// If we fail to load the image we will just not display it
this.bitmapImage.UriSource = null;
if (this.ShowDialogOnApiErrors)
{
await Util.GenericApiCallExceptionHandler(ex, "Error loading captured image.");
}
}
}
}
private async Task DetectAndShowFaceBorders()
{
this.progressIndicator.IsActive = true;
foreach (var child in this.hostGrid.Children.Where(c => !(c is Image)).ToArray())
{
this.hostGrid.Children.Remove(child);
}
if (this.DataContext is ImageAnalyzer imageWithFace)
{
if (imageWithFace.DetectedFaces == null)
{
await imageWithFace.DetectFacesAsync(detectFaceAttributes: this.DetectFaceAttributes, detectFaceLandmarks: this.DetectFaceLandmarks);
}
double renderedImageXTransform = this.imageControl.RenderSize.Width / this.bitmapImage.PixelWidth;
double renderedImageYTransform = this.imageControl.RenderSize.Height / this.bitmapImage.PixelHeight;
foreach (DetectedFace face in imageWithFace.DetectedFaces)
{
FaceIdentificationBorder faceUI = new FaceIdentificationBorder()
{
Tag = face.FaceId,
};
faceUI.Margin = new Thickness((face.FaceRectangle.Left * renderedImageXTransform) + ((this.ActualWidth - this.imageControl.RenderSize.Width) / 2),
(face.FaceRectangle.Top * renderedImageYTransform) + ((this.ActualHeight - this.imageControl.RenderSize.Height) / 2), 0, 0);
faceUI.BalloonBackground = this.BalloonBackground;
faceUI.BalloonForeground = this.BalloonForeground;
faceUI.ShowFaceRectangle(face.FaceRectangle.Width * renderedImageXTransform, face.FaceRectangle.Height * renderedImageYTransform);
if (this.ShowFaceLandmarks)
{
faceUI.ShowFaceLandmarks(renderedImageXTransform, renderedImageYTransform, face);
}
this.hostGrid.Children.Add(faceUI);
if (!this.ShowMultipleFaces)
{
break;
}
}
if (this.PerformRecognition)
{
if (imageWithFace.IdentifiedPersons == null)
{
await imageWithFace.IdentifyFacesAsync();
}
if (this.ShowRecognitionResults)
{
foreach (DetectedFace face in imageWithFace.DetectedFaces)
{
// Get the border for the associated face id
FaceIdentificationBorder faceUI = (FaceIdentificationBorder)this.hostGrid.Children.FirstOrDefault(e => e is FaceIdentificationBorder && (Guid)(e as FaceIdentificationBorder).Tag == face.FaceId);
if (faceUI != null)
{
IdentifiedPerson faceIdIdentification = imageWithFace.IdentifiedPersons.FirstOrDefault(p => p.FaceId == face.FaceId);
string name = this.DetectFaceAttributes && faceIdIdentification != null ? faceIdIdentification.Person.Name : null;
Microsoft.Azure.CognitiveServices.Vision.Face.Models.Gender? gender = this.DetectFaceAttributes ? face.FaceAttributes.Gender : null;
double age = this.DetectFaceAttributes ? face.FaceAttributes.Age.GetValueOrDefault() : 0;
double confidence = this.DetectFaceAttributes && faceIdIdentification != null ? faceIdIdentification.Confidence : 0;
faceUI.ShowIdentificationData(age, gender, (uint)Math.Round(confidence * 100), name);
}
}
}
}
}
this.progressIndicator.IsActive = false;
}
private async Task DetectAndShowComputerVisionAnalysis()
{
this.progressIndicator.IsActive = true;
this.imageControl.RenderTransform = null;
foreach (var child in this.hostGrid.Children.Where(c => !(c is Image)).ToArray())
{
this.hostGrid.Children.Remove(child);
}
if (this.DataContext is ImageAnalyzer img)
{
List<Task> tasks = new List<Task>();
if (img.AnalysisResult == null)
{
tasks.Add(img.AnalyzeImageAsync(new List<Details> { Details.Celebrities, Details.Landmarks }));
}
if (this.PerformOCRAnalysis && (img.TextOperationResult == null || img.TextRecognitionMode != this.TextRecognitionMode))
{
tasks.Add(img.RecognizeTextAsync(this.TextRecognitionMode));
}
if (this.PerformObjectDetection && img.DetectedObjects == null)
{
tasks.Add(img.DetectObjectsAsync());
}
await Task.WhenAll(tasks);
double renderedImageXTransform = this.imageControl.RenderSize.Width / this.bitmapImage.PixelWidth;
double renderedImageYTransform = this.imageControl.RenderSize.Height / this.bitmapImage.PixelHeight;
if (img.AnalysisResult.Faces != null)
{
foreach (FaceDescription face in img.AnalysisResult.Faces)
{
FaceIdentificationBorder faceUI = new FaceIdentificationBorder
{
Margin = new Thickness((face.FaceRectangle.Left * renderedImageXTransform) + ((this.ActualWidth - this.imageControl.RenderSize.Width) / 2),
(face.FaceRectangle.Top * renderedImageYTransform) + ((this.ActualHeight - this.imageControl.RenderSize.Height) / 2), 0, 0),
BalloonBackground = this.BalloonBackground,
BalloonForeground = this.BalloonForeground
};
faceUI.ShowFaceRectangle(face.FaceRectangle.Width * renderedImageXTransform, face.FaceRectangle.Height * renderedImageYTransform);
var faceGender = Util.GetFaceGender(face.Gender);
faceUI.ShowIdentificationData(face.Age, faceGender, 0, null);
this.hostGrid.Children.Add(faceUI);
this.GetCelebrityInfoIfAvailable(img, face.FaceRectangle, out string celebRecoName, out double celebRecoConfidence);
if (!string.IsNullOrEmpty(celebRecoName))
{
Border celebUI = new Border
{
Child = new TextBlock
{
Text = string.Format("{0} ({1}%)", celebRecoName, (uint)Math.Round(celebRecoConfidence * 100)),
Foreground = this.BalloonForeground,
FontSize = 14
},
Background = this.BalloonBackground,
VerticalAlignment = VerticalAlignment.Top,
HorizontalAlignment = HorizontalAlignment.Left
};
celebUI.SizeChanged += (ev, ar) =>
{
celebUI.Margin = new Thickness(faceUI.Margin.Left - (celebUI.ActualWidth - face.FaceRectangle.Width * renderedImageXTransform) / 2,
faceUI.Margin.Top + 2 + face.FaceRectangle.Height * renderedImageYTransform, 0, 0);
};
this.hostGrid.Children.Add(celebUI);
}
}
}
// Clean up any old results
foreach (var child in this.hostGrid.Children.Where(c => (c is OCRBorder)).ToArray())
{
this.hostGrid.Children.Remove(child);
}
// OCR request (Printed / Handwritten)
if (this.PerformOCRAnalysis && img.TextOperationResult?.RecognitionResult?.Lines != null)
{
this.imageControl.RenderTransform = new RotateTransform { Angle = 0, CenterX = this.imageControl.RenderSize.Width / 2, CenterY = this.imageControl.RenderSize.Height / 2 };
foreach (Line line in img.TextOperationResult.RecognitionResult.Lines)
{
foreach (var word in line.Words)
{
double[] boundingBox = word?.BoundingBox?.ToArray() ?? new double[] { };
if (boundingBox.Length == 8)
{
double minLeft = renderedImageXTransform * (new List<double>() { boundingBox[0], boundingBox[2], boundingBox[4], boundingBox[6] }).Min();
double minTop = renderedImageYTransform * (new List<double>() { boundingBox[1], boundingBox[3], boundingBox[5], boundingBox[7] }).Min();
var points = new PointCollection()
{
new Windows.Foundation.Point(boundingBox[0] * renderedImageXTransform - minLeft, boundingBox[1] * renderedImageYTransform - minTop),
new Windows.Foundation.Point(boundingBox[2] * renderedImageXTransform - minLeft, boundingBox[3] * renderedImageYTransform - minTop),
new Windows.Foundation.Point(boundingBox[4] * renderedImageXTransform - minLeft, boundingBox[5] * renderedImageYTransform - minTop),
new Windows.Foundation.Point(boundingBox[6] * renderedImageXTransform - minLeft, boundingBox[7] * renderedImageYTransform - minTop)
};
// The four points (x-coordinate, y-coordinate) of the detected rectangle from the left-top corner and clockwise
IEnumerable<Windows.Foundation.Point> leftPoints = points.OrderBy(p => p.X).Take(2);
IEnumerable<Windows.Foundation.Point> rightPoints = points.OrderByDescending(p => p.X).Take(2);
Windows.Foundation.Point leftTop = leftPoints.OrderBy(p => p.Y).FirstOrDefault();
Windows.Foundation.Point leftBottom = leftPoints.OrderByDescending(p => p.Y).FirstOrDefault();
Windows.Foundation.Point rightTop = rightPoints.OrderBy(p => p.Y).FirstOrDefault();
Windows.Foundation.Point rightBottom = rightPoints.OrderByDescending(p => p.Y).FirstOrDefault();
var orderedPoints = new PointCollection()
{
leftTop, rightTop, rightBottom, leftBottom
};
// simple math to get angle of the text
double diffWidth = Math.Abs(leftTop.X - rightTop.X);
double diffHeight = Math.Abs(leftTop.Y - rightTop.Y);
double sign = leftTop.Y > rightTop.Y ? -1 : 1;
double angle = sign * Math.Atan2(diffHeight, diffWidth) * (180 / Math.PI); // angle in degrees
OCRBorder ocrUI = new OCRBorder
{
Margin = new Thickness(minLeft + ((this.ActualWidth - this.imageControl.RenderSize.Width) / 2),
minTop + ((this.ActualHeight - this.imageControl.RenderSize.Height) / 2), 0, 0)
};
ocrUI.SetPoints(orderedPoints, word.Text, angle);
this.hostGrid.Children.Add(ocrUI);
}
}
}
}
if (this.PerformObjectDetection && img.DetectedObjects != null)
{
this.ShowObjectDetectionRegions(img.DetectedObjects);
}
}
this.progressIndicator.IsActive = false;
}
private void ShowObjectDetectionRegions(IEnumerable<DetectedObject> predictions)
{
double renderedImageXTransform = this.imageControl.RenderSize.Width / this.bitmapImage.PixelWidth;
double renderedImageYTransform = this.imageControl.RenderSize.Height / this.bitmapImage.PixelHeight;
foreach (DetectedObject prediction in predictions)
{
this.hostGrid.Children.Add(
new Border
{
BorderBrush = new SolidColorBrush(Colors.Lime),
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
BorderThickness = new Thickness(2),
Margin = new Thickness(prediction.Rectangle.X * renderedImageXTransform + ((this.ActualWidth - this.imageControl.RenderSize.Width) / 2),
prediction.Rectangle.Y * renderedImageYTransform + ((this.ActualHeight - this.imageControl.RenderSize.Height) / 2), 0, 0),
Width = prediction.Rectangle.W * renderedImageXTransform,
Height = prediction.Rectangle.H * renderedImageYTransform,
});
this.hostGrid.Children.Add(
new Border
{
Height = 40,
FlowDirection = FlowDirection.LeftToRight,
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
Margin = new Thickness(prediction.Rectangle.X * renderedImageXTransform + ((this.ActualWidth - this.imageControl.RenderSize.Width) / 2),
prediction.Rectangle.Y * renderedImageYTransform + ((this.ActualHeight - this.imageControl.RenderSize.Height) / 2) - 40, 0, 0),
Child = new Border
{
Background = new SolidColorBrush(Colors.Lime),
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Bottom,
Child =
new TextBlock
{
Foreground = new SolidColorBrush(Colors.Black),
Text = $"{prediction.ObjectProperty} ({Math.Round(prediction.Confidence * 100)}%)",
FontSize = 16,
Margin = new Thickness(6, 0, 6, 0)
}
}
});
}
}
private void GetCelebrityInfoIfAvailable(ImageAnalyzer analyzer, Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models.FaceRectangle rectangle, out string name, out double confidence)
{
if (analyzer.AnalysisResult?.Categories != null)
{
foreach (var category in analyzer.AnalysisResult.Categories.Where(c => c.Detail != null))
{
if (category.Detail.Celebrities != null)
{
foreach (var celebrity in category.Detail.Celebrities)
{
int left = celebrity.FaceRectangle.Left;
int top = celebrity.FaceRectangle.Top;
if (Math.Abs(left - rectangle.Left) <= 20 && Math.Abs(top - rectangle.Top) <= 20)
{
name = celebrity.Name;
confidence = celebrity.Confidence;
return;
}
}
}
}
}
name = null;
confidence = 0;
}
private async Task DetectAndShowEmotion()
{
this.progressIndicator.IsActive = true;
foreach (var child in this.hostGrid.Children.Where(c => !(c is Image)).ToArray())
{
this.hostGrid.Children.Remove(child);
}
if (this.DataContext is ImageAnalyzer imageWithFace)
{
if (imageWithFace.DetectedFaces == null)
{
await imageWithFace.DetectFacesAsync(detectFaceAttributes: true);
}
double renderedImageXTransform = this.imageControl.RenderSize.Width / this.bitmapImage.PixelWidth;
double renderedImageYTransform = this.imageControl.RenderSize.Height / this.bitmapImage.PixelHeight;
foreach (DetectedFace face in imageWithFace.DetectedFaces)
{
FaceIdentificationBorder faceUI = new FaceIdentificationBorder
{
Margin = new Thickness((face.FaceRectangle.Left * renderedImageXTransform) + ((this.ActualWidth - this.imageControl.RenderSize.Width) / 2),
(face.FaceRectangle.Top * renderedImageYTransform) + ((this.ActualHeight - this.imageControl.RenderSize.Height) / 2), 0, 0),
BalloonBackground = this.BalloonBackground,
BalloonForeground = this.BalloonForeground
};
faceUI.ShowFaceRectangle(face.FaceRectangle.Width * renderedImageXTransform, face.FaceRectangle.Height * renderedImageYTransform);
faceUI.ShowEmotionData(face.FaceAttributes.Emotion);
this.hostGrid.Children.Add(faceUI);
if (!this.ShowMultipleFaces)
{
break;
}
}
}
this.progressIndicator.IsActive = false;
}
private async Task PreviewImageFaces()
{
if (!this.DetectFacesOnLoad || this.progressIndicator.IsActive)
{
return;
}
if (this.DataContext is ImageAnalyzer img)
{
img.UpdateDecodedImageSize(this.bitmapImage.PixelHeight, this.bitmapImage.PixelWidth);
}
if (this.ShowEmotionRecognition)
{
await this.DetectAndShowEmotion();
}
else if (this.DetectFaceAttributes)
{
await this.DetectAndShowFaceBorders();
}
else if (this.PerformComputerVisionAnalysis)
{
await this.DetectAndShowComputerVisionAnalysis();
}
}
private async void OnBitmapImageOpened(object sender, RoutedEventArgs e)
{
await this.PreviewImageFaces();
}
private async void OnImageSizeChanged(object sender, SizeChangedEventArgs e)
{
await this.PreviewImageFaces();
}
}
}