in FamilyNotes/UserDetection/FacialSimilarity.cs [64:155]
public static async Task<int> TrainDetectionAsync()
{
StorageFolder LocalFolder = ApplicationData.Current.LocalFolder;
await _semaphore.WaitAsync();
await LoadSettingsAsync();
await CheckTransactionCapAsync();
_userImages.Clear();
_userFacialIDs.Clear();
_userNames.Clear();
int FacesAdded = 0;
// Find Users directory and load each folder of user images
try
{
StorageFolder Users = await LocalFolder.GetFolderAsync("Users");
IReadOnlyList<StorageFolder> UserDirectories = await Users.GetFoldersAsync();
foreach(StorageFolder UserFolder in UserDirectories)
{
string UserName = UserFolder.Name;
IReadOnlyList<StorageFile> UserPictures = await UserFolder.GetFilesAsync();
//Just retrieve the first image for each user, assuming the user has an image.
if (UserPictures.Any<StorageFile>())
{
_userImages.Add(UserName, UserPictures.First<StorageFile>());
}
}
}
catch (System.IO.FileNotFoundException)
{
_semaphore.Release();
return FacesAdded;
}
// Delete any existing FaceList held by the Azure Face service. Exception is thrown and surpressed if specified list didn't exist.
try
{
await WaitOnTransactionCapAsync();
await _faceClient.FaceList.DeleteAsync(_listKey);
_transactionCount++;
}
catch (Exception)
{
}
// Create a new FaceList in the Azure Face service for persistent Face storage.
try
{
await WaitOnTransactionCapAsync();
await _faceClient.FaceList.CreateAsync(_listKey, _listKey, "");
_transactionCount++;
}
catch (Exception)
{
_semaphore.Release();
return FacesAdded;
}
var UserNames = _userImages.Keys;
foreach(var UserName in UserNames)
{
var UserImageStorageFile = _userImages[UserName];
using(var UserImageFilestream = File.OpenRead(UserImageStorageFile.Path))
{
try
{
// Adds face to list and gets persistent face ID.
await WaitOnTransactionCapAsync();
var DetectedFaceID = await _faceClient.FaceList.AddFaceFromStreamAsync(_listKey, UserImageFilestream, UserName);
_transactionCount++;
_userFacialIDs.Add(UserName, DetectedFaceID.PersistedFaceId);
_userNames.Add(DetectedFaceID.PersistedFaceId, UserName);
FacesAdded++;
}
catch(Exception)
{
// This exception occurs when the Azure Face service AddFaceToListAsync call isn't able to detect a singlular face
// in the profile picture. Additional logic could be added to better determine the cause of failure and surface that to
// the app for retry.
}
}
}
InitialTrainingPerformed = true;
_semaphore.Release();
return FacesAdded;
}