Ejemplo n.º 1
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;
            }
        }
        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;
        }
Ejemplo n.º 3
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;
        }
Ejemplo n.º 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;
            }
        }
        //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);
        }
Ejemplo n.º 7
0
        private async void ExecuteCadastrarPessoaCommand()
        {
            try
            {
                await FaceServiceHelper.CreatePersonAsync(SelectedGroup.PersonGroupId, TextoPessoa);

                RefreshPeople();
                TextoPessoa = string.Empty;
            }
            catch (Exception ex) {}
        }
Ejemplo n.º 8
0
        private async Task CreatePersonAsync(string name)
        {
            try
            {
                await FaceServiceHelper.CreatePersonAsync(this.CurrentPersonGroup.PersonGroupId, Util.CapitalizeString(name));

                await this.LoadPersonsInCurrentGroup();

                this.DismissFlyout();
            }
            catch (Exception e)
            {
                await Util.GenericApiCallExceptionHandler(e, "Failure creating person");
            }
        }
Ejemplo n.º 9
0
        private async Task CreatePersonAsync(string name)
        {
            try
            {
                await FaceServiceHelper.CreatePersonAsync(this.CurrentPersonGroup.PersonGroupId, Util.CapitalizeString(name));

                await this.LoadPersonsInCurrentGroup();

                this.DismissFlyout();
            }
            catch (Exception e)
            {
                await Util.GenericApiCallExceptionHandler(e, AppResourcesHelper.GetString("PersonGroupDetailsPage_ErrorCreatePerson"));
            }
        }
        private async Task CreatePersonAsync(string name)
        {
            try
            {
                CreatePersonResult result = await FaceServiceHelper.CreatePersonAsync(this.CurrentPersonGroup.PersonGroupId, name);

                this.PersonsInCurrentGroup.Add(new Person {
                    Name = name, PersonId = result.PersonId
                });
                this.needsTraining = true;
                this.DismissFlyout();
            }
            catch (Exception e)
            {
                await Util.GenericApiCallExceptionHandler(e, "Failure creating person");
            }
        }
Ejemplo n.º 11
0
        public async Task <bool> CreatePersonAsync(string username)
        {
            try
            {
                Person person = await FaceServiceHelper.CreatePersonAsync(this.CurrentPersonGroup.PersonGroupId, username);

                this.PersonsInCurrentGroup.Add(new Person {
                    Name = username, PersonId = person.PersonId
                });
                SelectedPerson = PersonsInCurrentGroup.Last();
                return(true);
            }
            catch (Exception ex)
            {
                await Util.GenericApiCallExceptionHandler(ex, "Failure creating person");

                return(false);
            }
        }
        private async void getPredefinedStuff()
        {
            try
            {
                IEnumerable <PersonGroup> personGroups = await FaceServiceHelper.ListPersonGroupsAsync(SettingsHelper.Instance.WorkspaceKey);

                Person[] personsInGroup = await FaceServiceHelper.GetPersonsAsync(personGroups.FirstOrDefault().PersonGroupId);

                CreatePersonResult result = await FaceServiceHelper.CreatePersonAsync(personGroups.FirstOrDefault().PersonGroupId, "Rami");

                groupid   = personGroups.FirstOrDefault().PersonGroupId;
                persionID = result.PersonId;

                Constants.x = "1920";
                Constants.y = "1350";
            }
            catch (Exception ex)
            {
            }
        }
Ejemplo n.º 13
0
        private async static void GetCleberPhotosByEuCorro()
        {
            var    faceService   = new FaceDetectService();
            string personGroupId = "corridacleber161334";

            FaceServiceHelper.ApiKey       = "";
            FaceServiceHelper.ApiKeyRegion = "";

            //var ExistsPersonGroup = FaceServiceHelper.GetPersonGroupsAsync(personGroupId).Result.PersonGroupId == personGroupId;

            //if (!ExistsPersonGroup)
            //{

            //}

            await FaceServiceHelper.CreatePersonGroupAsync(personGroupId, "Night Running");

            CreatePersonResult cleber = await FaceServiceHelper.CreatePersonAsync(personGroupId, "Cleber");

            const string friend1ImageDir = @"C:\Users\clebe\Desktop\templatescleber";

            foreach (string imagePath in Directory.GetFiles(friend1ImageDir, "*.jpg"))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    try
                    {
                        await FaceServiceHelper.AddPersonFaceAsync(personGroupId, cleber.PersonId, s);
                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                }
            }

            await FaceServiceHelper.TrainPersonGroupAsync(personGroupId);

            TrainingStatus trainingStatus = null;

            while (true)
            {
                trainingStatus = await FaceServiceHelper.GetPersonGroupTrainingStatusAsync(personGroupId);

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

                await Task.Delay(1000);
            }

            //var countStart = 430067;
            var countStart = 432339;
            var countEnd   = 432484;

            var targetPath = $@"{friend1ImageDir}\result";

            if (!Directory.Exists(targetPath))
            {
                Directory.CreateDirectory(targetPath);
            }

            for (int i = countStart; i < countEnd; i++)
            {
                string url = $"http://www.eucorro.com/fotos/evento_427/maior/foto_{i}.jpg";

                var image = await faceService.DetectFacesByUrl(url);

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

                try
                {
                    var results = await FaceServiceHelper.IdentifyAsync(personGroupId, faceIds);

                    foreach (var identifyResult in results)
                    {
                        Console.WriteLine("Value i: {0}", i);
                        Console.WriteLine("");
                        Console.WriteLine("Result of face: {0}", identifyResult.FaceId);

                        if (identifyResult.Candidates.Length == 0)
                        {
                            Console.WriteLine("No one identified");
                        }
                        else
                        {
                            faceService.SaveImageByUrl(image, targetPath);
                        }
                    }
                }
                catch (Exception)
                {
                    continue;
                }
            }
        }
Ejemplo n.º 14
0
        public async Task Register()
        {
            IsRegistrationEnabled = false;
            try
            {
                IEnumerable <PersonGroup> PersonGroups = null;
                int i = 3; //retry count

                // 1. Select group
                // If the group is full, another one needs to added manually with alphabetically preceeding name
                do
                {
                    PersonGroups = await FaceServiceHelper.ListPersonGroupsAsync(SettingsHelper.Instance.WorkspaceKey);

                    if (PersonGroups.Count() > 0)
                    {
                        CurrentPersonGroup = PersonGroups.OrderBy(pg => pg.Name).First();
                    }
                    // Do not forget to create a persons group if there is not one
                    else
                    {
                        await FaceServiceHelper.CreatePersonGroupAsync(Guid.NewGuid().ToString(), "DefaultGroup", SettingsHelper.Instance.WorkspaceKey);
                    }

                    i--;
                } while (PersonGroups.Count() < 1 && i >= 0);

                // 2. Create a person in that group
                CurrentPerson = await FaceServiceHelper.CreatePersonAsync(this.CurrentPersonGroup.PersonGroupId, FullName);

                // 3. Add face to that person
                CurrentFace = await FaceServiceHelper.AddPersonFaceFromStreamAsync(
                    CurrentPersonGroup.PersonGroupId,
                    CurrentPerson.PersonId,
                    imageStreamCallback : customerFace.GetImageStreamCallback,
                    userData : customerFace.LocalImagePath,
                    targetFaceRect : null);

                // 4. Train model
                await FaceServiceHelper.TrainPersonGroupAsync(CurrentPersonGroup.PersonGroupId);

                bool trainingSucceeded = false;
                bool recordAdded       = false;

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

                    if (trainingStatus.Status == TrainingStatusType.Succeeded)
                    {
                        trainingSucceeded = true;
                        break;
                    }
                    else if (trainingStatus.Status == TrainingStatusType.Failed)
                    {
                        break;
                    }

                    await Task.Delay(100);
                }

                // 5. Add record to the database
                if (trainingSucceeded)
                {
                    customerInfo = new CustomerRegistrationInfo
                    {
                        CustomerFaceHash = CurrentPerson.PersonId.ToString(),
                        CustomerName     = FullName,
                        RegistrationDate = DateTime.Now
                    };

                    recordAdded = IgniteDataAccess.CreateCustomerRecord(customerInfo.CustomerFaceHash, customerInfo.CustomerName);
                }

                // 6. Update status
                if (trainingSucceeded && recordAdded)
                {
                    StatusText      = "Success!";
                    StatusTextColor = Util.ToBrush("green");
                }
                else
                {
                    customerInfo          = null;
                    IsRegistrationEnabled = true;
                    StatusText            = "Please try again later";
                    StatusTextColor       = Util.ToBrush("red");
                    ResumeCamera?.Invoke(this, EventArgs.Empty);
                }
            }
            catch (Exception)
            {
                customerInfo          = null;
                IsRegistrationEnabled = true;
                StatusText            = "Please try again";
                StatusTextColor       = Util.ToBrush("red");
                ResumeCamera?.Invoke(this, EventArgs.Empty);
            }
        }
        public async void FindByGroupPerson()
        {
            string personGroupId     = "formatura";
            var    ExistsPersonGroup = FaceServiceHelper.GetPersonGroupsAsync(personGroupId).Result.PersonGroupId == personGroupId;

            if (!ExistsPersonGroup)
            {
                await FaceServiceHelper.CreatePersonGroupAsync(personGroupId, "Minha formatura");
            }

            CreatePersonResult ana = await FaceServiceHelper.CreatePersonAsync(personGroupId, "Ana");

            const string friend1ImageDir = @"M:\Onedrive\Projetos\Detector Face beta\ana";

            foreach (string imagePath in Directory.GetFiles(friend1ImageDir, "*.jpg"))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    try
                    {
                        await FaceServiceHelper.AddPersonFaceAsync(personGroupId, ana.PersonId, s);
                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                }
            }

            await FaceServiceHelper.TrainPersonGroupAsync(personGroupId);

            TrainingStatus trainingStatus = null;

            while (true)
            {
                trainingStatus = await FaceServiceHelper.GetPersonGroupTrainingStatusAsync(personGroupId);

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

                await Task.Delay(1000);
            }

            string template = @"C:\Users\clebe\Desktop\template2.jpg";

            using (Stream s = File.OpenRead(template))
            {
                var faces = await FaceServiceHelper.DetectAsync(s);

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

                var results = await FaceServiceHelper.IdentifyAsync(personGroupId, faceIds);

                foreach (var identifyResult in results)
                {
                    Console.WriteLine("Result of face: {0}", identifyResult.FaceId);
                    if (identifyResult.Candidates.Length == 0)
                    {
                        Console.WriteLine("No one identified");
                    }
                    else
                    {
                        var candidateId = identifyResult.Candidates[0].PersonId;
                        var person      = await FaceServiceHelper.GetPersonAsync(personGroupId, candidateId);

                        Console.WriteLine("Identified as {0}", person.Name);
                    }
                }

                Console.ReadKey();
            }
        }
        private async Task ImportFromFolderAndFilesAsync(StorageFolder autoTrainFolder)
        {
            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) || this.PersonsInCurrentGroup.Any(p => p.Name == personName))
                    {
                        continue;
                    }

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

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

                    foreach (var photoFile in await folder.GetFilesAsync())
                    {
                        try
                        {
                            await FaceServiceHelper.AddPersonFaceAsync(
                                this.CurrentPersonGroup.PersonGroupId,
                                newPerson.PersonId,
                                imageStreamCallback : 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.needsTraining = true;

                    this.PersonsInCurrentGroup.Add(newPerson);
                }
            }
            catch (Exception ex)
            {
                await Util.GenericApiCallExceptionHandler(ex, "在處理資料夾和檔案時發生錯誤。");
            }

            if (errors.Any())
            {
                await new MessageDialog(string.Join("\n", errors), "引入照片失敗。").ShowAsync();
            }

            this.progressControl.IsActive = false;
        }