private async void OnConfirmImportButtonClicked(object sender, RoutedEventArgs e)
        {
            this.addPeopleInBatchesFlyout.Hide();
            this.commandBar.IsOpen = false;

            this.progressControl.IsActive = true;

            try
            {
                string[] names = this.importNamesTextBox.Text.Split('\n');
                foreach (var name in names)
                {
                    string personName = Util.CapitalizeString(name.Trim());
                    if (string.IsNullOrEmpty(personName) || this.PersonsInCurrentGroup.Any(p => p.Name == personName))
                    {
                        continue;
                    }

                    CreatePersonResult newPersonResult = await FaceServiceHelper.CreatePersonAsync(this.CurrentPersonGroup.PersonGroupId, personName);

                    Person newPerson = new Person {
                        Name = name, PersonId = newPersonResult.PersonId
                    };

                    IEnumerable <string> faceUrls = await BingSearchHelper.GetImageSearchResults(string.Format("{0} {1} {2}", this.importImageSearchKeywordPrefix.Text, name, this.importImageSearchKeywordSufix.Text), count : 2);

                    foreach (var url in faceUrls)
                    {
                        try
                        {
                            ImageAnalyzer imageWithFace = new ImageAnalyzer(url);

                            await imageWithFace.DetectFacesAsync();

                            if (imageWithFace.DetectedFaces.Count() == 1)
                            {
                                await FaceServiceHelper.AddPersonFaceAsync(this.CurrentPersonGroup.PersonGroupId, newPerson.PersonId, imageWithFace.ImageUrl, imageWithFace.ImageUrl, imageWithFace.DetectedFaces.First().FaceRectangle);
                            }
                        }
                        catch (Exception)
                        {
                            // Ignore errors with any particular image and continue
                        }

                        // Force a delay to reduce the chance of hitting API call rate limits
                        await Task.Delay(250);
                    }

                    this.needsTraining = true;

                    this.PersonsInCurrentGroup.Add(newPerson);
                }
            }
            catch (Exception ex)
            {
                await Util.GenericApiCallExceptionHandler(ex, "Failure during batch processing");
            }

            this.progressControl.IsActive = false;
        }
        public async Task TrainVisitorGroup(string groupId, bool waitForTrainingToComplete)
        {
            //var group = await identifiedVisitorGroupRepo.GetByIdAsync(groupId);
            //if (group != null)
            //{
            await FaceServiceHelper.TrainPersonGroupAsync(groupId);

            TrainingStatus trainingStatus = null;

            while (waitForTrainingToComplete)
            {
                trainingStatus = await GetVisitorsGroupTrainingStatusAsync(groupId);

                if (trainingStatus.Status != TrainingStatusType.Running)
                {
                    break;
                }

                await Task.Delay(1000);
            }

            //group.LastTrainingDate = DateTime.UtcNow;
            //await identifiedVisitorGroupRepo.UpdateAsync(group);
            //}
            //else
            //{
            //    throw new KeyNotFoundException($"Group ({groupId}) not found");
            //}
        }
예제 #3
0
        private async void RefreshPeople()
        {
            try
            {
                if (SelectedGroup == null)
                {
                    return;
                }
                var result = await FaceServiceHelper.GetPersonsAsync(SelectedGroup.PersonGroupId);

                People = new ObservableCollection <PeopleOveridden>();

                foreach (var item in result)
                {
                    People.Add(new PeopleOveridden
                    {
                        Name             = item.Name,
                        PersistedFaceIds = item.PersistedFaceIds,
                        PersonId         = item.PersonId,
                        UserData         = item.UserData
                    });
                }
            }
            catch (Exception ex) {}
        }
예제 #4
0
        //static string personGroupId;
        async Task RegisterFaces()
        {
            try
            {
                var persongroupId = Guid.NewGuid().ToString();
                await FaceServiceHelper.CreatePersonGroupAsync(persongroupId,
                                                               "Xamarin",
                                                               AppDelegate.WorkspaceKey);

                await FaceServiceHelper.CreatePersonAsync(persongroupId, "NISH ANIL");

                var personsInGroup = await FaceServiceHelper.GetPersonsAsync(persongroupId);

                await FaceServiceHelper.AddPersonFaceAsync(persongroupId, personsInGroup[0].PersonId,
                                                           "https://raw.githubusercontent.com/nishanil/Mods2016/master/Slides/nish-test.jpg", null, null);

                await FaceServiceHelper.TrainPersonGroupAsync(persongroupId);


                isFaceRegistered = true;
            }
            catch (FaceAPIException ex)

            {
                Console.WriteLine(ex.Message);
                isFaceRegistered = false;
            }
        }
        private async void OnAddPersonGroupButtonClicked(object sender, RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(SettingsHelper.Instance.WorkspaceKey))
                {
                    throw new InvalidOperationException("Before you can create groups you need to define a Workspace Key in the Settings Page.");
                }

                Guid personGroupGuid = Guid.NewGuid();
                await FaceServiceHelper.CreatePersonGroupAsync(personGroupGuid.ToString(), this.personGroupNameTextBox.Text, SettingsHelper.Instance.WorkspaceKey);

                PersonGroup newGroup = new PersonGroup {
                    Name = this.personGroupNameTextBox.Text, PersonGroupId = personGroupGuid.ToString()
                };

                this.PersonGroups.Add(newGroup);
                this.personGroupsListView.SelectedValue = newGroup;

                this.personGroupNameTextBox.Text = "";
                this.addPersonGroupFlyout.Hide();

                this.needsTraining = true;
            }
            catch (Exception ex)
            {
                await Util.GenericApiCallExceptionHandler(ex, "Failure creating group");
            }
        }
        /// <summary>
        /// Train whitelist until training finished
        /// </summary>
        /// <returns></returns>
        private async Task <bool> TrainingWhitelistAsync()
        {
            bool isSuccess = true;

            // Train whitelist after add all person
            Debug.WriteLine("Start training whitelist...");
            await FaceServiceHelper.TrainPersonGroupAsync(WhitelistId);

            ClientContract.TrainingStatus status;

            while (true)
            {
                status = await FaceServiceHelper.GetPersonGroupTrainingStatusAsync(WhitelistId);

                // if still running, continue to check status
                if (status.Status == ClientContract.Status.Running)
                {
                    continue;
                }

                // if timeout or failed
                if (status.Status != ClientContract.Status.Succeeded)
                {
                    isSuccess = false;
                }
                break;
            }

            return(isSuccess);
        }
예제 #7
0
        /*
         * public async void Initializev2()
         * {
         *  InitState = InitStates.InProgress;
         *  try
         *  {
         *      LoadRoamingSettings();
         *      Windows.Storage.ApplicationData.Current.DataChanged += RoamingDataChanged;
         *      da = new DataAccess();
         *
         *      if (localSettings.Values["DbConnString"] != null && localSettings.Values["CardConnString"] != null)
         *      {
         *          DbConnectionString = localSettings.Values["DbConnString"].ToString();
         *          CardConnString = localSettings.Values["CardConnString"].ToString();
         *          if (da.TestConnString(DbConnectionString) == true && da.TestConnString(CardConnString) == true)
         *          {
         *              da.StoreConnStrings(DbConnectionString, CardConnString);
         *              op = new Operations(DbConnectionString, CardConnString);
         *
         *              var selLocation = localSettings.Values["selectedLocation"];
         *
         *              if (selLocation != null)
         *              {
         *                  string selectedLocation = localSettings.Values["selectedLocation"].ToString();
         *
         *                  appLocation = await da.GetLocationById(selectedLocation);
         *                  if (appLocation != null && appLocation.isDisabled != true)
         *                  {
         *                      MinHours = await da.GetMinHours();
         *
         *                      // Gets the default user group for students or trainee
         *                      string groupIdString = await da.GetGlobalSetting("DefaultTraineeGroup");
         *                      int.TryParse(groupIdString, out int groupID);
         *                      defaultStudentGroup = await da.GetUserGroupById(groupID);
         *
         *                      // Gets the default user gorup for all other users
         *                      groupIdString = await da.GetGlobalSetting("DefaultGroup");
         *                      int.TryParse(groupIdString, out groupID);
         *                      defaultOtherGroup = await da.GetUserGroupById(groupID);
         *
         *                      InitState = InitStates.Success;
         *                      return;
         *                  }
         *              }
         *          }
         *          else
         *          {
         *              // Clears the saved connection string as it is invalid.
         *              localSettings.Values["DbConnString"] = null;
         *              localSettings.Values["CardConnString"] = null;
         *          }
         *      }
         *      InitState = InitStates.Completed;
         *      return;
         *  }
         *  catch (Exception)
         *  {
         *      InitState = InitStates.Failed;
         *  }
         * }
         */
        #endregion

        public async Task <bool> LoadRegisteredPeople()
        {
            try
            {
                PersonGroups.Clear();
                IEnumerable <PersonGroup> personGroups = await FaceServiceHelper.ListPersonGroupsAsync(this.WorkspaceKey);

                PersonGroups.AddRange(personGroups.OrderBy(pg => pg.Name));

                CurrentPersonGroup = personGroups.FirstOrDefault();

                PersonsInCurrentGroup.Clear();
                IList <Person> personsInGroup = await FaceServiceHelper.GetPersonsAsync(this.CurrentPersonGroup.PersonGroupId);

                foreach (Person person in personsInGroup.OrderBy(p => p.Name))
                {
                    this.PersonsInCurrentGroup.Add(person);
                }

                return(true);
            }
            catch (Exception ex)
            {
                await Util.GenericApiCallExceptionHandler(ex, "Failure loading Person Groups");

                return(false);
            }
        }
        private async Task LoadPersonFacesFromService()
        {
            this.progressControl.IsActive = true;

            this.SelectedPersonFaces.Clear();

            try
            {
                Person latestVersionOfCurrentPerson = await FaceServiceHelper.GetPersonAsync(this.CurrentPersonGroup.PersonGroupId, this.SelectedPerson.PersonId);

                this.SelectedPerson.PersistedFaceIds = latestVersionOfCurrentPerson.PersistedFaceIds;

                if (this.SelectedPerson.PersistedFaceIds != null)
                {
                    foreach (Guid face in this.SelectedPerson.PersistedFaceIds)
                    {
                        PersistedFace personFace = await FaceServiceHelper.GetPersonFaceAsync(this.CurrentPersonGroup.PersonGroupId, this.SelectedPerson.PersonId, face);

                        this.SelectedPersonFaces.Add(personFace);
                    }
                }
            }
            catch (Exception e)
            {
                await Util.GenericApiCallExceptionHandler(e, "Failure downloading person faces");
            }

            this.progressControl.IsActive = false;
        }
예제 #9
0
        /// <summary>
        /// Initializes face detection on the preview stream, from https://docs.microsoft.com/en-us/windows/uwp/audio-video-camera/scene-analysis-for-media-capture
        /// </summary>
        /// <returns></returns>
        public async Task InitializeFaceDetection()
        {
            // Load the face service client to to face recognition with Cognitive Services
            if (FaceService == null)
            {
                FaceService = await FaceServiceHelper.CreateNewFaceServiceAsync();
            }

            // Create the definition, which will contain some initialization settings
            var definition = new FaceDetectionEffectDefinition();

            // To ensure preview smoothness, do not delay incoming samples
            definition.SynchronousDetectionEnabled = false;

            // In this scenario, choose detection speed over accuracy
            definition.DetectionMode = FaceDetectionMode.HighPerformance;

            // Add the effect to the preview stream
            _faceDetectionEffect = (FaceDetectionEffect)await _mediaCapture.AddVideoEffectAsync(definition, MediaStreamType.VideoPreview);

            // TODO: Chance to a good frequency to save Cognitive Services API calls
            // Choose the shortest interval between detection events
            //_faceDetectionEffect.DesiredDetectionInterval = TimeSpan.FromMilliseconds(33);
            // Currently we offline detect faces every 3 seconds to save API calls
            _faceDetectionEffect.DesiredDetectionInterval = TimeSpan.FromMilliseconds(3000);

            // Start detecting faces
            _faceDetectionEffect.Enabled = true;

            // Register for face detection events
            _faceDetectionEffect.FaceDetected += FaceDetectionEffect_FaceDetected;

            _isDetecting = true;
        }
        //Groups
        public async Task <IdentifiedVisitorGroup> CreateVisitorsGroupAsync(string groupName)
        {
            IdentifiedVisitorGroup result = null;

            //var isValidGroupId = Regex.IsMatch(groupId, "^[a-z0-9-_]+");
            //if (!isValidGroupId)
            //    throw new InvalidExpressionException("Group id must be only alpha numeric letters with - and _");
            try
            {
                var newItem = new IdentifiedVisitorGroup
                {
                    Name         = groupName,
                    Filter       = faceWorkspaceDataFilter,
                    PartitionKey = AppConstants.DbColIdentifiedVisitorPartitionKeyValue,
                    IsActive     = true,
                    CreatedAt    = DateTime.UtcNow,
                    Origin       = AppConstants.Origin
                };

                result = await identifiedVisitorGroupRepo.AddAsync(newItem);

                result.GroupId = result.Id.ToLower();
                await FaceServiceHelper.CreatePersonGroupAsync(result.GroupId, newItem.Name, newItem.Filter);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(result);
        }
예제 #11
0
        public static async Task RegisterFaces()
        {
            try
            {
                var persongroupId = Guid.NewGuid().ToString();
                await FaceServiceHelper.CreatePersonGroupAsync(
                    persongroupId,
                    "Xamarin",
                    WorkspaceKey);

                await FaceServiceHelper.CreatePersonAsync(persongroupId, "Albert Einstein");

                var personsInGroup = await FaceServiceHelper.GetPersonsAsync(persongroupId);

                await FaceServiceHelper.AddPersonFaceAsync(
                    persongroupId,
                    personsInGroup[0].PersonId,
                    "https://upload.wikimedia.org/wikipedia/commons/d/d3/Albert_Einstein_Head.jpg",
                    null,
                    null);

                await FaceServiceHelper.TrainPersonGroupAsync(persongroupId);

                IsFaceRegistered = true;
            }
            catch (FaceAPIException ex)
            {
                //Console.WriteLine(ex.Message);
                IsFaceRegistered = false;
            }
        }
        public async Task InitializeAsync()
        {
            try
            {
                IsLoading = true;

                if (FaceService == null)
                {
                    FaceService = await FaceServiceHelper.CreateNewFaceServiceAsync();
                }

                var personGroupResult = await FaceService.ListPersonGroupsAsync();

                personGroupResult.OrderBy(pg => pg.Name);
                personGroupResult.ForEach(pg => PersonGroups.Add(pg));

                IsLoading = false;
            }
            catch (FaceAPIException ex)//Handle API-Exception
            {
                await MessageDialogHelper.MessageDialogAsync(ex.ErrorMessage);
            }
            catch (Exception ex)
            {
                await MessageDialogHelper.MessageDialogAsync(ex.Message);
            }
        }
예제 #13
0
        private static async Task AnalyzeFacesAsync(Func <Task <Stream> > imageStreamCallback, ImageInsights result)
        {
            var faces = await FaceServiceHelper.DetectAsync(imageStreamCallback, returnFaceId : true, returnFaceLandmarks : false, returnFaceAttributes : DefaultFaceAttributeTypes);

            List <FaceInsights> faceInsightsList = new List <FaceInsights>();

            foreach (Face detectedFace in faces)
            {
                FaceInsights faceInsights = new FaceInsights
                {
                    FaceRectangle = detectedFace.FaceRectangle,
                    Age           = detectedFace.FaceAttributes.Age,
                    Gender        = detectedFace.FaceAttributes.Gender
                };

                SimilarPersistedFace similarPersistedFace = await FaceListManager.FindSimilarPersistedFaceAsync(imageStreamCallback, detectedFace.FaceId, detectedFace);

                if (similarPersistedFace != null)
                {
                    faceInsights.UniqueFaceId = similarPersistedFace.PersistedFaceId;
                }

                faceInsightsList.Add(faceInsights);
            }

            result.FaceInsights = faceInsightsList.ToArray();
        }
예제 #14
0
        private async void ExecuteConfirmedCommand()
        {
            try
            {
                IsRunning = true;
                var result = await FaceServiceHelper.DetectAsync(GetStream, true);

                if (result == null || result.Count() == 0)
                {
                    return;
                }
                await FaceServiceHelper.AddPersonFaceAsync(SelectedGroup.PersonGroupId, SelectedPerson.PersonId, GetStream,
                                                           null, result.FirstOrDefault().FaceRectangle);

                await FaceServiceHelper.TrainPersonGroupAsync(SelectedGroup.PersonGroupId);

                ImageUrl = string.Empty;
                await _mvvmService.MessageMvvm("Mensagem", "Rosto cadastrado com sucesso", "Ok");
            }
            catch (Exception ex) { }
            finally
            {
                IsRunning = false;
            }
        }
        public async Task <Face[]> SimpleDetectFace(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 FaceServiceHelper.DetectAsync(imageFileStream, returnFaceId : true, returnFaceLandmarks : false, returnFaceAttributes : faceAttributes);

                    return(faces);
                }
            }
            // Catch and display Face API errors.
            catch (FaceAPIException f)
            {
                return(new Face[0]);
            }
            // Catch and display all other errors.
            catch (Exception e)
            {
                return(new Face[0]);
            }
        }
예제 #16
0
        private async void OnStartTrainingClicked(object sender, RoutedEventArgs e)
        {
            this.progressControl.IsActive = true;

            TrainingStatus trainingStatus = null;

            try
            {
                await FaceServiceHelper.TrainPersonGroupAsync(this.CurrentPersonGroup.PersonGroupId);

                while (true)
                {
                    trainingStatus = await FaceServiceHelper.GetPersonGroupTrainingStatusAsync(this.CurrentPersonGroup.PersonGroupId);

                    if (trainingStatus.Status != Status.Running)
                    {
                        break;
                    }
                    await Task.Delay(1000);
                }
            }
            catch (Exception ex)
            {
                await Util.GenericApiCallExceptionHandler(ex, "Failure requesting training");
            }

            this.progressControl.IsActive = false;

            if (trainingStatus.Status != Status.Succeeded)
            {
                await new MessageDialog("Training finished with failure.").ShowAsync();
            }
        }
예제 #17
0
        private async Task ImportFromFolderAndFilesAsync()
        {
            this.commandBar.IsOpen = false;

            this.progressControl.IsActive = true;

            List <string> errors = new List <string>();

            try
            {
                foreach (var folder in await autoTrainFolder.GetFoldersAsync())
                {
                    string personName = Util.CapitalizeString(folder.Name.Trim());
                    if (string.IsNullOrEmpty(personName))
                    {
                        continue;
                    }

                    if (!this.PersonsInCurrentGroup.Any(p => p.Name == personName))
                    {
                        await FaceServiceHelper.CreatePersonAsync(this.CurrentPersonGroup.PersonGroupId, personName);
                    }

                    Person newPerson = (await FaceServiceHelper.GetPersonsAsync(this.CurrentPersonGroup.PersonGroupId)).First(p => p.Name == personName);

                    foreach (var photoFile in await folder.GetFilesAsync())
                    {
                        try
                        {
                            await FaceServiceHelper.AddPersonFaceAsync(
                                this.CurrentPersonGroup.PersonGroupId,
                                newPerson.PersonId,
                                imageStream : await photoFile.OpenStreamForReadAsync(),
                                userData : photoFile.Path,
                                targetFace : null);

                            // Force a delay to reduce the chance of hitting API call rate limits
                            await Task.Delay(250);
                        }
                        catch (Exception)
                        {
                            errors.Add(photoFile.Path);
                        }
                    }

                    this.PersonsInCurrentGroup.Add(newPerson);
                }
            }
            catch (Exception ex)
            {
                await Util.GenericApiCallExceptionHandler(ex, "Failure processing the folder and files");
            }

            if (errors.Any())
            {
                await new MessageDialog(string.Join("\n", errors), "Failure importing the folllowing photos").ShowAsync();
            }

            this.progressControl.IsActive = false;
        }
        public async Task <ResultStatus> DeleteVisitorsGroup(string groupId)
        {
            var result = new ResultStatus();
            var group  = await identifiedVisitorGroupRepo.GetByIdAsync(groupId);

            if (group != null)
            {
                var visitorsInGroup = (await identifiedVisitorRepo.GetAllAsync()).Where(v => v.GroupId == group.Id);
                foreach (var visitor in visitorsInGroup)
                {
                    await identifiedVisitorRepo.DeleteAsync(visitor);
                }

                await FaceServiceHelper.DeletePersonGroupAsync(groupId);

                await identifiedVisitorGroupRepo.DeleteAsync(group);

                result.StatusCode   = "0";
                result.Message      = $"Successfully deleted group ({group.Id}) and the associated visitors ({visitorsInGroup.Count()}";
                result.IsSuccessful = true;
            }
            else
            {
                result.StatusCode   = "1";
                result.Message      = $"Group id ({group.Id}) not found!";
                result.IsSuccessful = false;
            }

            return(result);
        }
        public async void FindSimilarGroups()
        {
            var images = new List <Image>();

            const string imagemDir = @"M:\Onedrive\Projetos\Detector Face beta\Moda CESUMAR";

            foreach (string imagePath in Directory.GetFiles(imagemDir, "*.jpg"))
            {
                try
                {
                    Console.WriteLine($"image: {imagePath}");
                    var image = await DetectFaces(imagePath);

                    images.Add(image);
                }
                catch (Exception ex)
                {
                    continue;
                }
            }

            var faceIds = images.SelectMany(x => x.Faces).Select(t => t.FaceId).ToArray();

            GroupResult group = await FaceServiceHelper.GroupAsync(faceIds);

            CreateDirectoryByGroupResult(imagemDir, group, images);
        }
        private async Task AddTrainingImages(IEnumerable <ImageAnalyzer> args, bool dismissImageCollectorFlyout = true)
        {
            this.progressControl.IsActive = true;

            if (dismissImageCollectorFlyout)
            {
                this.trainingImageCollectorFlyout.Hide();
            }

            bool      foundError = false;
            Exception lastError  = null;

            foreach (var item in args)
            {
                try
                {
                    PersistedFace addResult;
                    if (item.GetImageStreamCallback != null)
                    {
                        addResult = await FaceServiceHelper.AddPersonFaceFromStreamAsync(
                            this.CurrentPersonGroup.PersonGroupId,
                            this.SelectedPerson.PersonId,
                            imageStreamCallback : item.GetImageStreamCallback,
                            userData : item.LocalImagePath,
                            targetFaceRect : null);
                    }
                    else
                    {
                        addResult = await FaceServiceHelper.AddPersonFaceFromUrlAsync(
                            this.CurrentPersonGroup.PersonGroupId,
                            this.SelectedPerson.PersonId,
                            imageUrl : item.ImageUrl,
                            userData : item.ImageUrl,
                            targetFaceRect : null);
                    }

                    if (addResult != null)
                    {
                        this.SelectedPersonFaces.Add(new PersistedFace {
                            PersistedFaceId = addResult.PersistedFaceId, UserData = item.GetImageStreamCallback != null ? item.LocalImagePath : item.ImageUrl
                        });
                        this.needsTraining = true;
                    }
                }
                catch (Exception e)
                {
                    foundError = true;
                    lastError  = e;
                }
            }

            if (foundError)
            {
                await Util.GenericApiCallExceptionHandler(lastError, "Failure adding one or more of the faces");
            }

            this.progressControl.IsActive = false;
        }
        //Visitors
        public async Task <IdentifiedVisitor> CreateVisitorAsync(IdentifiedVisitor identifiedVisitor)
        {
            //TODO: Validate if the visitor exists
            identifiedVisitor.CreatedAt    = DateTime.UtcNow;
            identifiedVisitor.IsActive     = true;
            identifiedVisitor.IsDeleted    = false;
            identifiedVisitor.PartitionKey = string.IsNullOrEmpty(identifiedVisitor.PartitionKey) ? AppConstants.DbColIdentifiedVisitorPartitionKeyValue : identifiedVisitor.PartitionKey;
            identifiedVisitor.Id           = $"{Guid.NewGuid().ToString()}-{identifiedVisitor.PartitionKey}";
            var cognitivePerson = await FaceServiceHelper.CreatePersonAsync(identifiedVisitor.GroupId, identifiedVisitor.Name, identifiedVisitor.Id);

            identifiedVisitor.PersonDetails = cognitivePerson;
            double?age    = null;
            Gender?gender = null;

            foreach (var photo in identifiedVisitor.Photos)
            {
                if (!photo.IsSaved)
                {
                    photoData = photo.PhotoData;
                    var photoFileExtension = Path.GetExtension(photo.Name);
                    var newPhotoFileName   = $"{identifiedVisitor.Id}-{identifiedVisitor.Photos.IndexOf(photo) + 1}{photoFileExtension}";

                    //Only accept photos with single face
                    var detectedFaces = await FaceServiceHelper.DetectWithStreamAsync(GetPhotoStream, returnFaceAttributes : faceAttributes);

                    if (detectedFaces.Count == 0)
                    {
                        photo.Status = "Invalid: No faces detected in photo";
                        continue;
                    }
                    else if (detectedFaces.Count > 1)
                    {
                        photo.Status = "Invalid: More than 1 face detected in photo. Only photos with single face can be used to train";
                        continue;
                    }

                    //Upload the new photo to storage
                    photo.Url = await storageRepo.CreateFileAsync(newPhotoFileName, photo.PhotoData);

                    age    = detectedFaces[0].FaceAttributes.Age;
                    gender = detectedFaces[0].FaceAttributes.Gender;
                    var persistedFace = await AddVisitorPhotoAsync(identifiedVisitor.GroupId, cognitivePerson.PersonId, photo.Url, detectedFaces[0].FaceRectangle);

                    //Update photo details
                    photo.IsSaved = true;
                    photo.Name    = newPhotoFileName;
                    photo.Status  = "Saved";
                }
            }

            //Save the new identified visitor details to database
            identifiedVisitor.Age    = age.HasValue ? age.Value : 0;
            identifiedVisitor.Gender = gender.HasValue ? gender.ToString() : "NA";

            var result = await identifiedVisitorRepo.AddAsync(identifiedVisitor);

            return(result);
        }
        /// <summary>
        /// Create a person into Face API and whitelist
        /// </summary>
        /// <param name="personName"></param>
        /// <param name="personFolder"></param>
        /// <returns></returns>
        private async Task <Guid> CreatePerson(string personName, StorageFolder personFolder)
        {
            var ret = await FaceServiceHelper.CreatePersonAsync(WhitelistId, personName);

            var personId = ret.PersonId;

            _whitelist.AddPerson(personId, personName, personFolder.Path);

            return(personId);
        }
        private async void OnImageSearchCompleted(object sender, IEnumerable <ImageAnalyzer> args)
        {
            this.progressControl.IsActive = true;

            this.trainingImageCollectorFlyout.Hide();

            bool      foundError = false;
            Exception lastError  = null;

            foreach (var item in args)
            {
                try
                {
                    AddPersistedFaceResult addResult;
                    if (item.GetImageStreamCallback != null)
                    {
                        addResult = await FaceServiceHelper.AddPersonFaceAsync(
                            this.CurrentPersonGroup.PersonGroupId,
                            this.SelectedPerson.PersonId,
                            imageStreamCallback : item.GetImageStreamCallback,
                            userData : item.LocalImagePath,
                            targetFace : null);
                    }
                    else
                    {
                        addResult = await FaceServiceHelper.AddPersonFaceAsync(
                            this.CurrentPersonGroup.PersonGroupId,
                            this.SelectedPerson.PersonId,
                            imageUrl : item.ImageUrl,
                            userData : item.ImageUrl,
                            targetFace : null);
                    }

                    if (addResult != null)
                    {
                        this.SelectedPersonFaces.Add(new PersonFace {
                            PersistedFaceId = addResult.PersistedFaceId, UserData = item.GetImageStreamCallback != null ? item.LocalImagePath : item.ImageUrl
                        });
                        this.needsTraining = true;
                    }
                }
                catch (Exception e)
                {
                    foundError = true;
                    lastError  = e;
                }
            }

            if (foundError)
            {
                await Util.GenericApiCallExceptionHandler(lastError, "增加一或多個臉孔時發生錯誤。");
            }

            this.progressControl.IsActive = false;
        }
예제 #24
0
        private async Task <string> CheckAuthorization()
        {
            try
            {
                FaceServiceHelper.ApiKey = COGNITIVE_KEY;

                var picture = await TakePicture();

                var personsGroups = await FaceServiceHelper.GetPersonGroupsAsync();

                if (personsGroups == null)
                {
                    return(null);
                }

                var gabGroup = personsGroups.FirstOrDefault(p => p.PersonGroupId == "2");

                var results = await FaceServiceHelper.DetectAsync(delegate { return(picture.OpenStreamForReadAsync()); },
                                                                  returnFaceId : true);

                if (results.Count() > 0)
                {
                    var faceId         = results.FirstOrDefault().FaceId;
                    var identityResult = await FaceServiceHelper.IdentifyAsync("2", new Guid[] { faceId });

                    var personId = identityResult.FirstOrDefault().Candidates
                                   .OrderBy(p => p.Confidence)
                                   .FirstOrDefault()
                                   .PersonId;

                    var personsInGabGroup = await FaceServiceHelper.GetPersonsAsync("2");

                    var authorized = personsInGabGroup.Any(p => p.PersonId == personId);

                    if (authorized)
                    {
                        var person = personsInGabGroup.FirstOrDefault(p => p.PersonId == personId);
                        hallPin.Write(GpioPinValue.High);
                        hallPin.SetDriveMode(GpioPinDriveMode.Output);
                        return(person.Name);
                    }
                }
                return(null);
            }
            catch (Exception ex)
            {
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                          () =>
                {
                    statusLabel.Text = ex.Message;
                });

                return(null);
            }
        }
        private async Task <Guid> SetupTemplate(string imagePath)
        {
            using (Stream s = File.OpenRead(imagePath))
            {
                var faces = await FaceServiceHelper.DetectAsync(s);

                var faceIds = faces.Select(face => face.FaceId).ToArray();

                return(faceIds.First());
            }
        }
예제 #26
0
        private async void ExecuteCadastrarPessoaCommand()
        {
            try
            {
                await FaceServiceHelper.CreatePersonAsync(SelectedGroup.PersonGroupId, TextoPessoa);

                RefreshPeople();
                TextoPessoa = string.Empty;
            }
            catch (Exception ex) {}
        }
예제 #27
0
        private async void ExecuteGrupoCommand()
        {
            try
            {
                await FaceServiceHelper.CreatePersonGroupAsync(Guid.NewGuid().ToString(), TextoGrupo, null);

                RefreshGroups();
                TextoGrupo = string.Empty;
            }
            catch (Exception ex) {}
        }
        public async Task <IdentifiedVisitor> UpdateVisitorAsync(IdentifiedVisitor identifiedVisitor)
        {
            if (identifiedVisitor == null)
            {
                throw new InvalidDataException("No visitor data");
            }

            if (identifiedVisitor.Photos != null && identifiedVisitor.Photos.Count > 0)
            {
                double?age    = null;
                Gender?gender = null;

                foreach (var photo in identifiedVisitor.Photos)
                {
                    if (!photo.IsSaved)
                    {
                        photoData = photo.PhotoData;
                        var photoFileExtension = Path.GetExtension(photo.Name);
                        var newPhotoFileName   = $"{identifiedVisitor.Id}-{identifiedVisitor.Photos.IndexOf(photo) + 1}{photoFileExtension}";

                        //Only accept photos with single face
                        var detectedFaces = await FaceServiceHelper.DetectWithStreamAsync(GetPhotoStream, returnFaceAttributes : faceAttributes);

                        if (detectedFaces.Count == 0)
                        {
                            photo.Status = "Invalid: No faces detected in photo";
                            continue;
                        }
                        else if (detectedFaces.Count > 1)
                        {
                            photo.Status = "Invalid: More than 1 face detected in photo. Only photos with single face can be used to train";
                            continue;
                        }

                        //Upload the new photo to storage
                        photo.Url = await storageRepo.CreateFileAsync(newPhotoFileName, photo.PhotoData);

                        age    = detectedFaces[0].FaceAttributes.Age;
                        gender = detectedFaces[0].FaceAttributes.Gender;
                        var persistedFace = await AddVisitorPhotoAsync(identifiedVisitor.GroupId, identifiedVisitor.PersonDetails.PersonId, photo.Url, detectedFaces[0].FaceRectangle);

                        //Update photo details
                        photo.IsSaved = true;
                        photo.Name    = newPhotoFileName;
                        photo.Status  = "Saved";
                    }
                }
            }
            await identifiedVisitorRepo.UpdateAsync(identifiedVisitor);

            return(identifiedVisitor);
        }
        private async Task DeletePersonAsync()
        {
            try
            {
                await FaceServiceHelper.DeletePersonAsync(this.CurrentPersonGroup.PersonGroupId, this.SelectedPerson.PersonId);

                this.PersonsInCurrentGroup.Remove(this.SelectedPerson);
            }
            catch (Exception ex)
            {
                await Util.GenericApiCallExceptionHandler(ex, "Failure deleting person");
            }
        }
예제 #30
0
        private async Task DeletePersonGroupAsync()
        {
            try
            {
                await FaceServiceHelper.DeletePersonGroupAsync(this.CurrentPersonGroup.PersonGroupId);

                this.Frame.GoBack();
            }
            catch (Exception ex)
            {
                await Util.GenericApiCallExceptionHandler(ex, "Failure deleting person group");
            }
        }