forked from microsoft/Cognitive-Samples-IntelligentKiosk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImageCollectionInsights.xaml.cs
352 lines (305 loc) · 14.6 KB
/
ImageCollectionInsights.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
//
// 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.ProjectOxford.Face.Contract;
using Newtonsoft.Json;
using ServiceHelpers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Search;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
namespace IntelligentKioskSample.Views.ImageCollectionInsights
{
[KioskExperience(Title = "Image Collection Insights", ImagePath = "ms-appx:/Assets/ImageCollectionInsights.jpg", ExperienceType = ExperienceType.Other)]
public sealed partial class ImageCollectionInsights : Page
{
private StorageFolder currentRootFolder;
public List<ImageInsightsViewModel> AllResults { get; set; } = new List<ImageInsightsViewModel>();
public ObservableCollection<ImageInsightsViewModel> FilteredResults { get; set; } = new ObservableCollection<ImageInsightsViewModel>();
public ObservableCollection<TagFilterViewModel> TagFilters { get; set; } = new ObservableCollection<TagFilterViewModel>();
public ObservableCollection<FaceFilterViewModel> FaceFilters { get; set; } = new ObservableCollection<FaceFilterViewModel>();
public ObservableCollection<EmotionFilterViewModel> EmotionFilters { get; set; } = new ObservableCollection<EmotionFilterViewModel>();
public ImageCollectionInsights()
{
this.InitializeComponent();
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
if (string.IsNullOrEmpty(SettingsHelper.Instance.FaceApiKey) ||
string.IsNullOrEmpty(SettingsHelper.Instance.VisionApiKey))
{
await new MessageDialog("Missing Face or Vision API Key. Please enter a key in the Settings page.", "Missing API Key").ShowAsync();
}
base.OnNavigatedTo(e);
}
private async void ProcessImagesClicked(object sender, RoutedEventArgs e)
{
try
{
FolderPicker folderPicker = new FolderPicker();
folderPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
folderPicker.FileTypeFilter.Add("*");
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
await ProcessImagesAsync(folder);
}
this.currentRootFolder = folder;
}
catch (Exception ex)
{
await Util.GenericApiCallExceptionHandler(ex, "Error picking the target folder.");
}
}
private async void ReProcessImagesClicked(object sender, RoutedEventArgs e)
{
await this.ProcessImagesAsync(this.currentRootFolder, forceProcessing: true);
}
private async Task ProcessImagesAsync(StorageFolder rootFolder, bool forceProcessing = false)
{
this.progressRing.IsActive = true;
this.landingMessage.Visibility = Visibility.Collapsed;
this.filterTab.Visibility = Visibility.Visible;
this.reprocessImagesButton.IsEnabled = true;
this.FilteredResults.Clear();
this.AllResults.Clear();
this.TagFilters.Clear();
this.EmotionFilters.Clear();
this.FaceFilters.Clear();
List<ImageInsights> insightsList = new List<ImageInsights>();
if (!forceProcessing)
{
// see if we have pre-computed results and if so load it from the json file
try
{
StorageFile insightsResultFile = (await rootFolder.TryGetItemAsync("ImageInsights.json")) as StorageFile;
if (insightsResultFile != null)
{
using (StreamReader reader = new StreamReader(await insightsResultFile.OpenStreamForReadAsync()))
{
insightsList = JsonConvert.DeserializeObject<List<ImageInsights>>(await reader.ReadToEndAsync());
foreach (var insights in insightsList)
{
await AddImageInsightsToViewModel(rootFolder, insights);
}
}
}
}
catch
{
// We will just compute everything again in case of errors
}
}
if (!insightsList.Any())
{
// start with fresh face lists
await FaceListManager.ResetFaceLists();
// enumerate through the images and extract the insights
QueryOptions fileQueryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, new[] { ".png", ".jpg", ".bmp", ".jpeg", ".gif" });
StorageFileQueryResult queryResult = rootFolder.CreateFileQueryWithOptions(fileQueryOptions);
var queryFileList = this.limitProcessingToggleButton.IsChecked.Value ? await queryResult.GetFilesAsync(0, 50) : await queryResult.GetFilesAsync();
foreach (var item in queryFileList)
{
// Resize (if needed) in order to reduce network latency. Then store the result in a temporary file.
StorageFile resizedFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("ImageCollectionInsights.jpg", CreationCollisionOption.GenerateUniqueName);
var resizeTransform = await Util.ResizePhoto(await item.OpenStreamForReadAsync(), 720, resizedFile);
// Send the file for processing
ImageInsights insights = await ImageProcessor.ProcessImageAsync(resizedFile.OpenStreamForReadAsync, item.Name);
// Delete resized file
await resizedFile.DeleteAsync();
// Adjust all FaceInsights coordinates based on the transform function between the original and resized photos
foreach (var faceInsight in insights.FaceInsights)
{
faceInsight.FaceRectangle.Left = (int) (faceInsight.FaceRectangle.Left * resizeTransform.Item1);
faceInsight.FaceRectangle.Top = (int)(faceInsight.FaceRectangle.Top * resizeTransform.Item2);
faceInsight.FaceRectangle.Width = (int)(faceInsight.FaceRectangle.Width * resizeTransform.Item1);
faceInsight.FaceRectangle.Height = (int)(faceInsight.FaceRectangle.Height * resizeTransform.Item2);
}
insightsList.Add(insights);
await AddImageInsightsToViewModel(rootFolder, insights);
}
// save to json
StorageFile jsonFile = await rootFolder.CreateFileAsync("ImageInsights.json", CreationCollisionOption.ReplaceExisting);
using (StreamWriter writer = new StreamWriter(await jsonFile.OpenStreamForWriteAsync()))
{
string jsonStr = JsonConvert.SerializeObject(insightsList, Formatting.Indented);
await writer.WriteAsync(jsonStr);
}
}
List<TagFilterViewModel> tagsGroupedByCountAndSorted = new List<TagFilterViewModel>();
foreach (var group in this.TagFilters.GroupBy(t => t.Count).OrderByDescending(g => g.Key))
{
tagsGroupedByCountAndSorted.AddRange(group.OrderBy(t => t.Tag));
}
this.TagFilters.Clear();
this.TagFilters.AddRange(tagsGroupedByCountAndSorted);
var sortedEmotions = this.EmotionFilters.OrderByDescending(e => e.Count).ToArray();
this.EmotionFilters.Clear();
this.EmotionFilters.AddRange(sortedEmotions);
var sortedFaces = this.FaceFilters.OrderByDescending(f => f.Count).ToArray();
this.FaceFilters.Clear();
this.FaceFilters.AddRange(sortedFaces);
this.progressRing.IsActive = false;
}
private async Task AddImageInsightsToViewModel(StorageFolder rootFolder, ImageInsights insights)
{
// Load image from file
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync((await (await rootFolder.GetFileAsync(insights.ImageId)).OpenStreamForReadAsync()).AsRandomAccessStream());
bitmapImage.DecodePixelHeight = 360;
// Create the view models
ImageInsightsViewModel insightsViewModel = new ImageInsightsViewModel(insights, bitmapImage);
this.AllResults.Add(insightsViewModel);
this.FilteredResults.Add(insightsViewModel);
foreach (var tag in insights.VisionInsights.Tags)
{
TagFilterViewModel tvm = this.TagFilters.FirstOrDefault(t => t.Tag == tag);
if (tvm == null)
{
tvm = new TagFilterViewModel(tag);
this.TagFilters.Add(tvm);
}
tvm.Count++;
}
foreach (var faceInsights in insights.FaceInsights)
{
FaceFilterViewModel fvm = this.FaceFilters.FirstOrDefault(f => f.FaceId == faceInsights.UniqueFaceId);
if (fvm == null)
{
StorageFile file = (await rootFolder.GetFileAsync(insights.ImageId));
ImageSource croppedFaced = await Util.GetCroppedBitmapAsync(
file.OpenStreamForReadAsync,
new FaceRectangle { Height = faceInsights.FaceRectangle.Height, Width = faceInsights.FaceRectangle.Width, Left = faceInsights.FaceRectangle.Left, Top = faceInsights.FaceRectangle.Top });
fvm = new FaceFilterViewModel(faceInsights.UniqueFaceId, croppedFaced);
this.FaceFilters.Add(fvm);
}
fvm.Count++;
}
var distinctEmotions = insights.FaceInsights.Select(f => f.TopEmotion).Distinct();
foreach (var emotion in distinctEmotions)
{
EmotionFilterViewModel evm = this.EmotionFilters.FirstOrDefault(f => f.Emotion == emotion);
if (evm == null)
{
evm = new EmotionFilterViewModel(emotion);
this.EmotionFilters.Add(evm);
}
evm.Count++;
}
}
private void ApplyFilters()
{
this.FilteredResults.Clear();
var checkedTags = this.TagFilters.Where(t => t.IsChecked);
var checkedFaces = this.FaceFilters.Where(f => f.IsChecked);
var checkedEmotions = this.EmotionFilters.Where(e => e.IsChecked);
if (checkedTags.Any() || checkedFaces.Any() || checkedEmotions.Any())
{
var fromTags = this.AllResults.Where(r => HasTag(checkedTags, r.Insights.VisionInsights.Tags));
var fromFaces = this.AllResults.Where(r => HasFace(checkedFaces, r.Insights.FaceInsights));
var fromEmotion = this.AllResults.Where(r => HasEmotion(checkedEmotions, r.Insights.FaceInsights));
this.FilteredResults.AddRange((fromTags.Concat(fromFaces).Concat(fromEmotion)).Distinct());
}
else
{
this.FilteredResults.AddRange(this.AllResults);
}
}
private bool HasFace(IEnumerable<FaceFilterViewModel> checkedFaces, FaceInsights[] faceInsights)
{
foreach (var item in checkedFaces)
{
if (faceInsights.Any(f => f.UniqueFaceId == item.FaceId))
{
return true;
}
}
return false;
}
private bool HasEmotion(IEnumerable<EmotionFilterViewModel> checkedEmotions, FaceInsights[] faceInsights)
{
foreach (var item in checkedEmotions)
{
if (faceInsights.Any(f => f.TopEmotion == item.Emotion))
{
return true;
}
}
return false;
}
private bool HasTag(IEnumerable<TagFilterViewModel> checkedTags, string[] tags)
{
foreach (var item in checkedTags)
{
if (tags.Any(t => t == item.Tag))
{
return true;
}
}
return false;
}
private void TagFilterChanged(object sender, RoutedEventArgs e)
{
this.ApplyFilters();
}
private void FaceFilterChanged(object sender, RoutedEventArgs e)
{
this.ApplyFilters();
}
private void EmotionFilterChanged(object sender, RoutedEventArgs e)
{
this.ApplyFilters();
}
}
public static class Extensions
{
public static void AddRange<T>(this IList<T> list, IEnumerable<T> items)
{
foreach (var item in items)
{
list.Add(item);
}
}
}
}