Ejemplo n.º 1
0
        /// <summary>
        /// Creates a training group.  
        /// </summary>
        /// <param name="PersonGroupID">Name of the person group.</param>
        /// <returns></returns>
        public async Task createFaceGroup(string PersonGroupID)
        {
            bool groupExists = false;
            IFaceServiceClient faceClient = new FaceServiceClient(SubscriptionKey);
            
            // Test whether the group already exists
            try
            {
                await faceClient.GetPersonGroupAsync(PersonGroupID);
                groupExists = true;
            }
            catch (ClientException ex)
            {
                if (ex.Error.Code != "PersonGroupNotFound")
                {
                    throw;
                }
                else
                {

                }
            }

            // check to see if group exists and if so delete the group.
            if (groupExists)
            {
                await faceClient.DeletePersonGroupAsync(PersonGroupID);
            }

            try
            {
                await faceClient.CreatePersonGroupAsync(PersonGroupID, PersonGroupID);
            }
            catch (ClientException ex)
            {
                throw;
            }



        }
        /// <summary>
        /// Command function to add a new person group. Makes sure the given names does not already exist
        /// </summary>
        /// <param name="obj"></param>
        private async void AddPersonGroup(object obj)
        {
            try
            {
                if (await DoesPersonGroupExistAsync(PersonGroupName.ToLower()))
                {
                    StatusText = $"Person group {PersonGroupName} already exists";
                    return;
                }

                await _faceServiceClient.CreatePersonGroupAsync(PersonGroupName.ToLower(), PersonGroupName);

                StatusText = $"Person group {PersonGroupName} added";
                GetPersonGroups();
            }
            catch (FaceAPIException ex)
            {
                StatusText = $"Failed to add person group: {ex.ErrorMessage}";
            }
            catch (Exception ex)
            {
                StatusText = $"Failed to add person group: {ex.Message}";
            }
        }
Ejemplo n.º 3
0
 public async Task CreatePersonGroupAsync(string personGroupId, string name, string userData)
 {
     await RunTaskWithAutoRetryOnQuotaLimitExceededError(() => faceClient.CreatePersonGroupAsync(personGroupId, name, userData));
 }
Ejemplo n.º 4
0
        public static async Task <string> AddFace(MemoryStream faceStream, string personName, string groupId, string groupDisplayName, FaceServiceClient FaceClient, bool showMsgBox = true)
        {
            string statusStr;

            try
            {
                // Does PersonGroup already exist
                try
                {
                    await FaceClient.GetPersonGroupAsync(groupId);
                }
                catch (Exception)
                {
                    // person group does not exist - create it
                    await FaceClient.CreatePersonGroupAsync(groupId, groupDisplayName);

                    // FIX there needs to be a wait or something to detect the new personGroup
                    await FaceClient.GetPersonGroupAsync(groupId);
                }
                //Get list of faces if any
                Person[] people = await FaceClient.ListPersonsAsync(groupId);

                Person p = people.FirstOrDefault(myP => myP.Name.Equals(personName, StringComparison.OrdinalIgnoreCase));
                Guid   personId;
                if (p != null)
                {
                    // person already exists - train our model to include new picture
                    personId = p.PersonId;
                }
                else
                {
                    // personGroupId is the group to add the person to, personName is what the user typed in to identify this face
                    CreatePersonResult myPerson = await FaceClient.CreatePersonAsync(groupId, personName);

                    personId = myPerson.PersonId;
                }
                // Person - List Persons in a Person Group
                // Detect faces in the image and add
                await FaceClient.AddPersonFaceAsync(groupId, personId, faceStream);

                // whenever we add a face, docs says we need to retrain - do it!

                //await retrainPersonGroup(_options.PersonGroupId);

                //// I think this is needed
                await FaceClient.TrainPersonGroupAsync(groupId);

                while (true)
                {
                    TrainingStatus trainingStatus = await FaceClient.GetPersonGroupTrainingStatusAsync(groupId);

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

                    await Task.Delay(1000);
                }

                statusStr = $@"A new face with name '{personName}' has been added and / or trained successfully in the personGroup '{groupId}'";

                //await UpdatePersonListAsync();
                //await _frmMain.UpdatePersonListAsync();
            }
            catch (Exception ex)
            {
                statusStr = $@"Unhandled excpetion while trying to add face: {ex.Message}";
            }

            if (showMsgBox)
            {
                MessageBox.Show(statusStr);
            }
            return(statusStr);
        }
Ejemplo n.º 5
0
 [HttpPut] //The Cognitive Services API is also a PUT, so I'm duplicating this here.
 public async Task CreatePersonGroup(string id, string name, string userData)
 {
     await FaceServiceClient.CreatePersonGroupAsync(id, name, userData);
 }
Ejemplo n.º 6
0
        static async void GroupTest()
        {
            FaceServiceClient faceServiceClient = new FaceServiceClient(subscriptionKey.ToString(), "https://northeurope.api.cognitive.microsoft.com/face/v1.0/");
            // Create an empty person group
            string personGroupId = "facegroup";

            try
            {
                await faceServiceClient.CreatePersonGroupAsync(personGroupId, "My Friends");

                Console.WriteLine("Group created");
            }
            catch
            {
                Console.WriteLine("Group Exists");
            }


            CreatePersonResult friend1 = await faceServiceClient.CreatePersonAsync(
                // Id of the person group that the person belonged to
                personGroupId,
                // Name of the person
                "Gunnar"
                );

            CreatePersonResult friend2 = await faceServiceClient.CreatePersonAsync(
                // Id of the person group that the person belonged to
                personGroupId,
                // Name of the person
                "Hallur"
                );

            var          i = 0;
            const string friend1ImageDir = @"C:\Users\ÓliJón\Pictures\FaceApiTest\Gunnar";
            var          test            = Directory.GetFiles(friend1ImageDir, "*.jpg");

            foreach (string imagePath in Directory.GetFiles(friend1ImageDir, "*.jpg"))
            {
                i++;
                using (Stream s = File.OpenRead(imagePath))
                {
                    // Detect faces in the image and add to Anna
                    await faceServiceClient.AddPersonFaceAsync(
                        personGroupId, friend1.PersonId, s);

                    Console.WriteLine("Gunnar picture: " + i);
                }
            }

            const string friend2ImageDir = @"C:\Users\ÓliJón\Pictures\FaceApiTest\Hallur";

            i = 0;
            foreach (string imagePath in Directory.GetFiles(friend2ImageDir, "*.jpg"))
            {
                i++;
                using (Stream s = File.OpenRead(imagePath))
                {
                    // Detect faces in the image and add to Anna
                    await faceServiceClient.AddPersonFaceAsync(
                        personGroupId, friend2.PersonId, s);

                    Console.WriteLine("Hallur picture: " + i);
                }
            }

            await faceServiceClient.TrainPersonGroupAsync(personGroupId);

            TrainingStatus trainingStatus = null;

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

                if (trainingStatus.Status.ToString() != "running")
                {
                    break;
                }


                await Task.Delay(3000);
            }
            await Task.Delay(3000);

            string testImageFile = @"C:\Users\ÓliJón\Pictures\FaceApiTest\tester\test.jpg";


            using (Stream s = File.OpenRead(testImageFile))
            {
                var faces = await faceServiceClient.DetectAsync(s);

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

                var results = await faceServiceClient.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
                    {
                        // Get top 1 among all candidates returned
                        var candidateId = identifyResult.Candidates[0].PersonId;
                        var person      = await faceServiceClient.GetPersonAsync(personGroupId, candidateId);

                        Console.WriteLine("Identified as {0}, Confidence: {1}", person.Name, identifyResult.Candidates[0].Confidence);
                    }
                }
            }
        }
Ejemplo n.º 7
0
 private async Task CreateAPersonGroupLogicalContainerAsync(string personGroupId, string personGroupName)
 {
     _waitCall.AddCallTimeToQueue();
     await _faceServiceClient.CreatePersonGroupAsync(personGroupId, personGroupName);
 }
        /// <summary>
        /// Pick the root person database folder, to minimum the data preparation logic, the folder should be under following construction
        /// Each person's image should be put into one folder named as the person's name
        /// All person's image folder should be put directly under the root person database folder
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event argument</param>
        private async void FolderPicker_Click(object sender, RoutedEventArgs e)
        {
            bool groupExists = false;

            MainWindow mainWindow = Window.GetWindow(this) as MainWindow;
            string subscriptionKey = mainWindow._scenariosControl.SubscriptionKey;

            var faceServiceClient = new FaceServiceClient(subscriptionKey);

            // Test whether the group already exists
            try
            {
                MainWindow.Log("Request: Group {0} will be used for build person database. Checking whether group exists.", GroupName);

                await faceServiceClient.GetPersonGroupAsync(GroupName);
                groupExists = true;
                MainWindow.Log("Response: Group {0} exists.", GroupName);
            }
            catch (FaceAPIException ex)
            {
                if (ex.ErrorCode != "PersonGroupNotFound")
                {
                    MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                    return;
                }
                else
                {
                    MainWindow.Log("Response: Group {0} does not exist before.", GroupName);
                }
            }

            if (groupExists)
            {
                var cleanGroup = System.Windows.MessageBox.Show(string.Format("Requires a clean up for group \"{0}\" before setup new person database. Click OK to proceed, group \"{0}\" will be fully cleaned up.", GroupName), "Warning", MessageBoxButton.OKCancel);
                if (cleanGroup == MessageBoxResult.OK)
                {
                    await faceServiceClient.DeletePersonGroupAsync(GroupName);
                }
                else
                {
                    return;
                }
            }

            // Show folder picker
            System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
            var result = dlg.ShowDialog();

            // Set the suggestion count is intent to minimum the data preparation step only,
            // it's not corresponding to service side constraint
            const int SuggestionCount = 15;

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                // User picked a root person database folder
                // Clear person database
                Persons.Clear();
                TargetFaces.Clear();
                SelectedFile = null;

                // Call create person group REST API
                // Create person group API call will failed if group with the same name already exists
                MainWindow.Log("Request: Creating group \"{0}\"", GroupName);
                try
                {
                    await faceServiceClient.CreatePersonGroupAsync(GroupName, GroupName);
                    MainWindow.Log("Response: Success. Group \"{0}\" created", GroupName);
                }
                catch (FaceAPIException ex)
                {
                    MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                    return;
                }

                int processCount = 0;
                bool forceContinue = false;

                MainWindow.Log("Request: Preparing faces for identification, detecting faces in chosen folder.");

                // Enumerate top level directories, each directory contains one person's images
                foreach (var dir in System.IO.Directory.EnumerateDirectories(dlg.SelectedPath))
                {
                    var tasks = new List<Task>();
                    var tag = System.IO.Path.GetFileName(dir);
                    Person p = new Person();
                    p.PersonName = tag;

                    var faces = new ObservableCollection<Face>();
                    p.Faces = faces;

                    // Call create person REST API, the new create person id will be returned
                    MainWindow.Log("Request: Creating person \"{0}\"", p.PersonName);
                    p.PersonId = (await faceServiceClient.CreatePersonAsync(GroupName, p.PersonName)).PersonId.ToString();
                    MainWindow.Log("Response: Success. Person \"{0}\" (PersonID:{1}) created", p.PersonName, p.PersonId);

                    // Enumerate images under the person folder, call detection
                    foreach (var img in System.IO.Directory.EnumerateFiles(dir, "*.jpg", System.IO.SearchOption.AllDirectories))
                    {
                        tasks.Add(Task.Factory.StartNew(
                            async (obj) =>
                            {
                                var imgPath = obj as string;

                                using (var fStream = File.OpenRead(imgPath))
                                {
                                    try
                                    {
                                        // Update person faces on server side
                                        var persistFace = await faceServiceClient.AddPersonFaceAsync(GroupName, Guid.Parse(p.PersonId), fStream, imgPath);
                                        return new Tuple<string, ClientContract.AddPersistedFaceResult>(imgPath, persistFace);
                                    }
                                    catch (FaceAPIException)
                                    {
                                        // Here we simply ignore all detection failure in this sample
                                        // You may handle these exceptions by check the Error.Error.Code and Error.Message property for ClientException object
                                        return new Tuple<string, ClientContract.AddPersistedFaceResult>(imgPath, null);
                                    }
                                }
                            },
                            img).Unwrap().ContinueWith((detectTask) =>
                            {
                                // Update detected faces for rendering
                                var detectionResult = detectTask.Result;
                                if (detectionResult == null || detectionResult.Item2 == null)
                                {
                                    return;
                                }

                                this.Dispatcher.Invoke(
                                    new Action<ObservableCollection<Face>, string, ClientContract.AddPersistedFaceResult>(UIHelper.UpdateFace),
                                    faces,
                                    detectionResult.Item1,
                                    detectionResult.Item2);
                            }));
                        if (processCount >= SuggestionCount && !forceContinue)
                        {
                            var continueProcess = System.Windows.Forms.MessageBox.Show("The images loaded have reached the recommended count, may take long time if proceed. Would you like to continue to load images?", "Warning", System.Windows.Forms.MessageBoxButtons.YesNo);
                            if (continueProcess == System.Windows.Forms.DialogResult.Yes)
                            {
                                forceContinue = true;
                            }
                            else
                            {
                                break;
                            }
                        }
                    }

                    Persons.Add(p);

                    await Task.WhenAll(tasks);
                }

                MainWindow.Log("Response: Success. Total {0} faces are detected.", Persons.Sum(p => p.Faces.Count));

                try
                {
                    // Start train person group
                    MainWindow.Log("Request: Training group \"{0}\"", GroupName);
                    await faceServiceClient.TrainPersonGroupAsync(GroupName);

                    // Wait until train completed
                    while (true)
                    {
                        await Task.Delay(1000);
                        var status = await faceServiceClient.GetPersonGroupTrainingStatusAsync(GroupName);
                        MainWindow.Log("Response: {0}. Group \"{1}\" training process is {2}", "Success", GroupName, status.Status);
                        if (status.Status != Contract.Status.Running)
                        {
                            break;
                        }
                    }
                }
                catch (FaceAPIException ex)
                {
                    MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                }
            }
        }
        /// <summary>
        /// Pick the root person database folder, to minimum the data preparation logic, the folder should be under following construction
        /// Each person's image should be put into one folder named as the person's name
        /// All person's image folder should be put directly under the root person database folder
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event argument</param>
        private async void FolderPicker_Click(object sender, RoutedEventArgs e)
        {
            bool groupExists = false;

            MainWindow mainWindow      = Window.GetWindow(this) as MainWindow;
            string     subscriptionKey = mainWindow._scenariosControl.SubscriptionKey;

            var faceServiceClient = new FaceServiceClient(subscriptionKey);

            // Test whether the group already exists
            try
            {
                MainWindow.Log("Request: Group {0} will be used for build person database. Checking whether group exists.", GroupName);

                await faceServiceClient.GetPersonGroupAsync(GroupName);

                groupExists = true;
                MainWindow.Log("Response: Group {0} exists.", GroupName);
            }
            catch (FaceAPIException ex)
            {
                if (ex.ErrorCode != "PersonGroupNotFound")
                {
                    MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                    return;
                }
                else
                {
                    MainWindow.Log("Response: Group {0} does not exist before.", GroupName);
                }
            }

            if (groupExists)
            {
                var cleanGroup = System.Windows.MessageBox.Show(string.Format("Requires a clean up for group \"{0}\" before setup new person database. Click OK to proceed, group \"{0}\" will be fully cleaned up.", GroupName), "Warning", MessageBoxButton.OKCancel);
                if (cleanGroup == MessageBoxResult.OK)
                {
                    await faceServiceClient.DeletePersonGroupAsync(GroupName);
                }
                else
                {
                    return;
                }
            }

            // Show folder picker
            System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
            var result = dlg.ShowDialog();

            // Set the suggestion count is intent to minimum the data preparation step only,
            // it's not corresponding to service side constraint
            const int SuggestionCount = 15;

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                // User picked a root person database folder
                // Clear person database
                Persons.Clear();
                TargetFaces.Clear();
                SelectedFile = null;

                // Call create person group REST API
                // Create person group API call will failed if group with the same name already exists
                MainWindow.Log("Request: Creating group \"{0}\"", GroupName);
                try
                {
                    await faceServiceClient.CreatePersonGroupAsync(GroupName, GroupName);

                    MainWindow.Log("Response: Success. Group \"{0}\" created", GroupName);
                }
                catch (FaceAPIException ex)
                {
                    MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                    return;
                }

                int  processCount  = 0;
                bool forceContinue = false;

                MainWindow.Log("Request: Preparing faces for identification, detecting faces in chosen folder.");

                // Enumerate top level directories, each directory contains one person's images
                foreach (var dir in System.IO.Directory.EnumerateDirectories(dlg.SelectedPath))
                {
                    var    tasks = new List <Task>();
                    var    tag   = System.IO.Path.GetFileName(dir);
                    Person p     = new Person();
                    p.PersonName = tag;

                    var faces = new ObservableCollection <Face>();
                    p.Faces = faces;

                    // Call create person REST API, the new create person id will be returned
                    MainWindow.Log("Request: Creating person \"{0}\"", p.PersonName);
                    p.PersonId = (await faceServiceClient.CreatePersonAsync(GroupName, p.PersonName)).PersonId.ToString();
                    MainWindow.Log("Response: Success. Person \"{0}\" (PersonID:{1}) created", p.PersonName, p.PersonId);

                    // Enumerate images under the person folder, call detection
                    foreach (var img in System.IO.Directory.EnumerateFiles(dir, "*.jpg", System.IO.SearchOption.AllDirectories))
                    {
                        tasks.Add(Task.Factory.StartNew(
                                      async(obj) =>
                        {
                            var imgPath = obj as string;

                            using (var fStream = File.OpenRead(imgPath))
                            {
                                try
                                {
                                    // Update person faces on server side
                                    var persistFace = await faceServiceClient.AddPersonFaceAsync(GroupName, Guid.Parse(p.PersonId), fStream, imgPath);
                                    return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, persistFace));
                                }
                                catch (FaceAPIException)
                                {
                                    // Here we simply ignore all detection failure in this sample
                                    // You may handle these exceptions by check the Error.Error.Code and Error.Message property for ClientException object
                                    return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, null));
                                }
                            }
                        },
                                      img).Unwrap().ContinueWith((detectTask) =>
                        {
                            // Update detected faces for rendering
                            var detectionResult = detectTask.Result;
                            if (detectionResult == null || detectionResult.Item2 == null)
                            {
                                return;
                            }

                            this.Dispatcher.Invoke(
                                new Action <ObservableCollection <Face>, string, ClientContract.AddPersistedFaceResult>(UIHelper.UpdateFace),
                                faces,
                                detectionResult.Item1,
                                detectionResult.Item2);
                        }));
                        if (processCount >= SuggestionCount && !forceContinue)
                        {
                            var continueProcess = System.Windows.Forms.MessageBox.Show("The images loaded have reached the recommended count, may take long time if proceed. Would you like to continue to load images?", "Warning", System.Windows.Forms.MessageBoxButtons.YesNo);
                            if (continueProcess == System.Windows.Forms.DialogResult.Yes)
                            {
                                forceContinue = true;
                            }
                            else
                            {
                                break;
                            }
                        }
                    }

                    Persons.Add(p);

                    await Task.WhenAll(tasks);
                }

                MainWindow.Log("Response: Success. Total {0} faces are detected.", Persons.Sum(p => p.Faces.Count));

                try
                {
                    // Start train person group
                    MainWindow.Log("Request: Training group \"{0}\"", GroupName);
                    await faceServiceClient.TrainPersonGroupAsync(GroupName);

                    // Wait until train completed
                    while (true)
                    {
                        await Task.Delay(1000);

                        var status = await faceServiceClient.GetPersonGroupTrainingStatusAsync(GroupName);

                        MainWindow.Log("Response: {0}. Group \"{1}\" training process is {2}", "Success", GroupName, status.Status);
                        if (status.Status != Contract.Status.Running)
                        {
                            break;
                        }
                    }
                }
                catch (FaceAPIException ex)
                {
                    MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                }
            }
        }
Ejemplo n.º 10
0
 public async void CreatePersonGroup(string groupID, string groupName)
 {
     await faceClient.CreatePersonGroupAsync(groupID, groupName);
 }
Ejemplo n.º 11
0
        static async void train()
        {
            FaceServiceClient faceServiceClient = new FaceServiceClient("XXXXXXXXXXXXXXXX");

            // Create an empty person group
            string personGroupId = "test1";
            await faceServiceClient.CreatePersonGroupAsync(personGroupId, "Test 1");

            CreatePersonResult friend1 = await faceServiceClient.CreatePersonAsync(personGroupId, "Anna");

            CreatePersonResult friend2 = await faceServiceClient.CreatePersonAsync(personGroupId, "Bill");

            CreatePersonResult friend3 = await faceServiceClient.CreatePersonAsync(personGroupId, "Clare");

            // Directory contains image files of Anna
            const string friend1ImageDir = @"C:\Users\StanDotloe\OneDrive\Facial Recognition\Projects\Cognitive-Face-Windows-master\Data\PersonGroup\Family3-Lady";
            const string friend2ImageDir = @"C:\Users\StanDotloe\OneDrive\Facial Recognition\Projects\Cognitive-Face-Windows-master\Data\PersonGroup\Family1-Dad";
            const string friend3ImageDir = @"C:\Users\StanDotloe\OneDrive\Facial Recognition\Projects\Cognitive-Face-Windows-master\Data\PersonGroup\Family1-Mom";

            foreach (string imagePath in Directory.GetFiles(friend1ImageDir, "*.jpg"))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    // Detect faces in the image and add to Anna
                    await faceServiceClient.AddPersonFaceAsync(
                        personGroupId, friend1.PersonId, s);
                }
            }

            foreach (string imagePath in Directory.GetFiles(friend2ImageDir, "*.jpg"))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    await faceServiceClient.AddPersonFaceAsync(personGroupId, friend2.PersonId, s);
                }
            }

            foreach (string imagePath in Directory.GetFiles(friend3ImageDir, "*.jpg"))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    await faceServiceClient.AddPersonFaceAsync(personGroupId, friend3.PersonId, s);
                }
            }

            await faceServiceClient.TrainPersonGroupAsync(personGroupId);

            TrainingStatus trainingStatus = null;

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

                if (!(trainingStatus.Status.Equals("running")))
                {
                    break;
                }

                await Task.Delay(1000);
            }


            string testImageFile = @"C:\Users\StanDotloe\OneDrive\Facial Recognition\Projects\Cognitive-Face-Windows-master\Data\PersonGroup\Family3-Man\Family3-Man3.jpg";

            using (Stream s = File.OpenRead(testImageFile))
            {
                var faces = await faceServiceClient.DetectAsync(s);

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

                var results = await faceServiceClient.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
                    {
                        // Get top 1 among all candidates returned
                        var candidateId = identifyResult.Candidates[0].PersonId;
                        var person      = await faceServiceClient.GetPersonAsync(personGroupId, candidateId);

                        Console.WriteLine("Identified as {0}", person.Name);
                    }
                }
            }
        }
Ejemplo n.º 12
0
 public async Task AddPersonGroup(PersonGroup group)
 {
     await _faceServiceClient.CreatePersonGroupAsync(group.PersonGroupId, group.Name);
 }
Ejemplo n.º 13
0
 static Task CreatePersonGroupTask()
 {
     //#1. API to create a group of persons
     return(faceServiceClient.CreatePersonGroupAsync(personGroupId, "My Friends"));
 }
Ejemplo n.º 14
0
        public async static void CreatePersonGroup()
        {
            await faceServiceClient.CreatePersonGroupAsync(personGroupId, "dataformers employees");

            var alexander = await faceServiceClient.CreatePersonAsync(personGroupId, "alexander");

            var anna = await faceServiceClient.CreatePersonAsync(personGroupId, "anna");

            var bernhard = await faceServiceClient.CreatePersonAsync(personGroupId, "bernhard");

            var david = await faceServiceClient.CreatePersonAsync(personGroupId, "david");

            var johannes = await faceServiceClient.CreatePersonAsync(personGroupId, "johannes");

            var lisa = await faceServiceClient.CreatePersonAsync(personGroupId, "lisa");

            var martina = await faceServiceClient.CreatePersonAsync(personGroupId, "martina");

            var norbert = await faceServiceClient.CreatePersonAsync(personGroupId, "norbert");

            var rene = await faceServiceClient.CreatePersonAsync(personGroupId, "rene");

            var sabine = await faceServiceClient.CreatePersonAsync(personGroupId, "sabine");

            var sarah = await faceServiceClient.CreatePersonAsync(personGroupId, "sarah");

            var sebastian = await faceServiceClient.CreatePersonAsync(personGroupId, "sebastian");

            var stefan = await faceServiceClient.CreatePersonAsync(personGroupId, "stefan");

            var tom = await faceServiceClient.CreatePersonAsync(personGroupId, "tom");

            var wilfried = await faceServiceClient.CreatePersonAsync(personGroupId, "wilfried");

            var employees = new Dictionary <string, CreatePersonResult>()
            {
                { "alexander", alexander },
                { "anna", anna },
                { "bernhard", bernhard },
                { "david", david },
                { "johannes", johannes },
                { "lisa", lisa },
                { "martina", martina },
                { "norbert", norbert },
                { "rene", rene },
                { "sabine", sabine },
                { "sarah", sarah },
                { "sebastian", sebastian },
                { "stefan", stefan },
                { "tom", tom },
                { "wilfried", wilfried }
            };

            foreach (var dir in Directory.GetDirectories(@"C:\projects\FaceIdentification\FaceIdentification\faces"))
            {
                foreach (var file in Directory.GetFiles(dir))
                {
                    using (Stream s = File.OpenRead(file))
                    {
                        var directoryName = new DirectoryInfo(dir).Name;
                        await faceServiceClient.AddPersonFaceAsync(personGroupId, employees.First(x => x.Key == directoryName).Value.PersonId, s);
                    }
                    Thread.Sleep(100);
                }
            }

            await faceServiceClient.TrainPersonGroupAsync(personGroupId);
        }
Ejemplo n.º 15
0
        private async Task TrainIt(IProgress <string> progress)
        {
            progress.Report("Creating Person Group");

            var key               = ConfigurationManager.AppSettings["subscriptionKey"];
            var apiRoot           = ConfigurationManager.AppSettings["apiRoot"];
            var faceServiceClient = new FaceServiceClient(key, apiRoot);

            var samplesDir = ConfigurationManager.AppSettings["samplesDir"];

            string personGroupId = "test-group";

            try
            {
                await faceServiceClient.DeletePersonGroupAsync(personGroupId);
            }
            catch (Exception ex)
            {
                progress.Report($"Delete Person Group Error: {ex.Message}");
            }

            try
            {
                await faceServiceClient.CreatePersonGroupAsync(personGroupId, "Test Group");
            }
            catch (Exception ex)
            {
                progress.Report($"Create Person Group Error: {ex.Message}");
            }

            var personGroupDir = System.IO.Path.Combine(samplesDir, "PersonGroup");

            DirectoryInfo di = new DirectoryInfo(personGroupDir);

            var personDirectories = di.GetDirectories();

            foreach (var personDirectory in personDirectories)
            {
                string personName = personDirectory.Name;

                progress.Report($"Adding '{personName}'");

                CreatePersonResult person = await faceServiceClient.CreatePersonAsync(
                    // group id
                    personGroupId,
                    // person name
                    personName);

                foreach (var image in personDirectory.GetFiles("*.jpg"))
                {
                    using (Stream s = File.OpenRead(image.FullName))
                    {
                        await faceServiceClient.AddPersonFaceAsync(
                            personGroupId,
                            person.PersonId,
                            s);
                    }
                }
            }

            progress.Report("Training Person Group");

            await faceServiceClient.TrainPersonGroupAsync(personGroupId);

            TrainingStatus trainingStatus = null;

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

                var status = trainingStatus.Status.ToString().ToLower();

                if (status != "running")
                {
                    break;
                }

                await Task.Delay(1000);
            }

            progress.Report("Upload image for identification");

            string testImageFile = System.IO.Path.Combine(samplesDir, @"identification3.jpg");

            using (Stream s = File.OpenRead(testImageFile))
            {
                var faces = await faceServiceClient.DetectAsync(s);

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

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

                foreach (var identifyResult in results)
                {
                    progress.Report($"Result of face: {identifyResult.FaceId}");
                    if (identifyResult.Candidates.Length == 0)
                    {
                        progress.Report("No one identified");
                    }
                    else
                    {
                        // Get top 1 among all candidates returned
                        var candidateId = identifyResult.Candidates[0].PersonId;
                        var person      = await faceServiceClient.GetPersonAsync(personGroupId, candidateId);

                        progress.Report($"Identified as {person.Name}");
                    }
                }
            }

            progress.Report("Done");
        }
Ejemplo n.º 16
0
 public void CreatePersonGroup(string personGroupId, string name, string userData = null)
 {
     _fsClient.CreatePersonGroupAsync(personGroupId, name, userData);
 }
Ejemplo n.º 17
0
        // Robin Added :Now you are ready to call the Face API from your application.


        /// <summary>
        //////////////
        ///  Button click triggers Create a group, add friends to that group, bind photos to each person
        /// </summary>
        // --------- Robin Added for the _Click -----------------
        public async void BrowseButton_Click1(object sender, RoutedEventArgs e)
        {
            // ======================================================================================================================

            /*
             *          // Decalare Variables
             *          bool groupExists = false;
             *
             *          // Below is to open a Dialog to get the file name, pop up the dialog box: openDlg.ShowDialog(this);
             *          // Eventually skip the open dialog, and just go read the files directly
             *          var openDlg = new Microsoft.Win32.OpenFileDialog();
             *
             *          openDlg.Filter = "JPEG Image(*.jpg)|*.jpg";
             *          bool? result = openDlg.ShowDialog(this);
             *
             *          if (!(bool)result)
             *          {
             *              return;
             *          }
             *
             */


            /*
             *          // Step 1 : getting those photos directories and its photo
             *          // hard code the root folder for all image sub folder, it starts in this folder and search down :
             *          //                C:\Users\v-role\Desktop\TestPhotos\SingleImage\
             *          // store the file name
             *          string filePath = openDlg.FileName;    // filePath is the image file name, I want to skip this method
             *
             *          // example to get its folder name
             *          FileInfo fInfo = new FileInfo(filePath);
             *          String FolderName = fInfo.Directory.Name;
             *
             *
             *
             *          //  example to get the Full path of that file
             *          String tmprootFolderName = System.IO.Path.GetDirectoryName(filePath);  // this is the root folder
             *          System.IO.DirectoryInfo rootFolderName = new System.IO.DirectoryInfo(tmprootFolderName);  // this is the root folder
             *
             *
             *          myoutputBox.Text += "Folder Name = "+ FolderName + "      File Name = "+ filePath+ " \n";
             *          myoutputBox.Text += "Root Folder Name = " + tmprootFolderName + "   File Name = " + filePath + " \n";
             */

            /*
             *          //////////////////////  group creation
             *
             *          // Step 2 : Test whether the group already exists
             *          try
             *          {
             *              myoutputBox.Text += "* Request: GroupID : " + GroupName + " will be used for build person database. \n       Checking whether group " + GroupName + " exists...\n";
             *
             *              await faceServiceClient.GetPersonGroupAsync(GroupName);
             *
             *              groupExists = true;
             *              myoutputBox.Text += "* Response: Group " + GroupName + " exists. \n";
             *          }
             *          catch (FaceAPIException ex)
             *          {
             *              if (ex.ErrorCode != "PersonGroupNotFound")
             *              {
             *                  myoutputBox.Text += "* Response: " + ex.ErrorCode + " : " + ex.ErrorMessage + "\n";
             *                  return;
             *              }
             *              else
             *              {
             *                  myoutputBox.Text += "* Response: GroupID " + GroupName + " does not exist before. \n";
             *              }
             *          }
             *
             *          //  Well, if that GroupID already exist, first Delete it
             *          if (groupExists)
             *          {
             *              myoutputBox.Text += "* Response: GroupID " + GroupName + " exists before. We are deleting it to start a new Group ID\n";
             *              await faceServiceClient.DeletePersonGroupAsync(GroupName);
             *          }
             *
             *          else   // group not exist, use the new groupId to create the new group, usually this is the case.
             *          {
             *              // Call create person group REST API
             *              // Create person group API call will failed if group with the same name already exists
             *              myoutputBox.Text += "* Request: Creating group with GroupID  " + GroupName + " \n";
             *              try
             *              {
             *                  await faceServiceClient.CreatePersonGroupAsync(GroupName, GroupName);
             *                  myoutputBox.Text += "* Response: Success. Group ID " + GroupName + " created \n";
             *              }
             *              catch (FaceAPIException ex)
             *              {
             *                  myoutputBox.Text += "* Response: " + ex.ErrorCode + " : " + ex.ErrorMessage + "\n";
             *
             *                  return;
             *              }
             *
             *              ////////////////////// End  group creation
             *          }
             *
             *
             */



            // ======================================================================================================================
            myoutputBox.Text += " A Moment Please ...    \n";

            System.Threading.Thread.Sleep(5000);

            // Create an empty person group
            //          string personGroupId = "myfriends";
            await faceServiceClient.CreatePersonGroupAsync(personGroupId, "MyFriends");

            // Define WongChiMan
            CreatePersonResult friend1 = await faceServiceClient.CreatePersonAsync(
                // Id of the person group that the person belonged to
                personGroupId,
                // Name of the person
                "Wong Chi Man"
                );

            // Define WongSumWai and TsangChiWai in the same way
            // Define Wong Sum Wing
            CreatePersonResult friend2 = await faceServiceClient.CreatePersonAsync(
                // Id of the person group that the person belonged to
                personGroupId,
                // Name of the person
                "Wong Sum Wing"
                );

            // Define TsangChiWai
            CreatePersonResult friend3 = await faceServiceClient.CreatePersonAsync(
                // Id of the person group that the person belonged to
                personGroupId,
                // Name of the person
                "Tsang Chi Wai"
                );

            // Define Robin
            CreatePersonResult friend4 = await faceServiceClient.CreatePersonAsync(
                // Id of the person group that the person belonged to
                personGroupId,
                // Name of the person
                "Robin"
                );

            myoutputBox.Text += " There are 4 friends I know:    \n";


            // Directory contains image files of WongChiMan
            const string friend1ImageDir = @"C:\TestPhotos\SingleImage\WongChiMan\";

            foreach (string imagePath in Directory.GetFiles(friend1ImageDir, "*.jpg"))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    // Detect faces in the image and add to Anna
                    await faceServiceClient.AddPersonFaceAsync(
                        personGroupId, friend1.PersonId, s);
                }
            }
            myoutputBox.Text += " Wong Chi Man,  ";

            // Do the same for WongSumWai and TsangChiWai


            // Directory contains image files of Anna
            const string friend2ImageDir = @"C:\TestPhotos\SingleImage\WongSumWai\";

            foreach (string imagePath in Directory.GetFiles(friend2ImageDir, "*.jpg"))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    // Detect faces in the image and add to WongSumWai
                    await faceServiceClient.AddPersonFaceAsync(
                        personGroupId, friend2.PersonId, s);
                }
            }
            myoutputBox.Text += " Wong Sum Wing,    ";


            // Directory contains image files of Anna
            const string friend3ImageDir = @"C:\TestPhotos\SingleImage\TsangChiWai\";

            foreach (string imagePath in Directory.GetFiles(friend3ImageDir, "*.jpg"))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    // Detect faces in the image and add to TsangChiWai
                    await faceServiceClient.AddPersonFaceAsync(
                        personGroupId, friend3.PersonId, s);
                }
            }
            myoutputBox.Text += " Tsang Chi Wai,    ";

            // Directory contains image files of Anna
            const string friend4ImageDir = @"C:\TestPhotos\SingleImage\Robin\";

            foreach (string imagePath in Directory.GetFiles(friend4ImageDir, "*.jpg"))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    // Detect faces in the image and add to Robin
                    await faceServiceClient.AddPersonFaceAsync(
                        personGroupId, friend4.PersonId, s);
                }
            }
            myoutputBox.Text += " Robin     \n";



            // Train the group
            myoutputBox.Text += " \n \n * A Moment Please ...Training the group in progress ............... ";

            await faceServiceClient.TrainPersonGroupAsync(personGroupId);

            System.Threading.Thread.Sleep(10000);

            myoutputBox.Text += "         * Success : Training the group ...............  \n \n";
            myoutputBox.Text += "* Please Click the button *Upload Photo* or *Take a Photo* To Authenticate you \n";
            myoutputBox.Text += "\n * ============================================================ \n";

            BrowseButton1.IsEnabled   = false;
            BrowseButton2.IsEnabled   = true;
            TakePhotoButton.IsEnabled = true;
        }        //  ---------  End Robin Added for the BrowseButton_Click1   ------------------
Ejemplo n.º 18
0
 public async Task CreatePersonGroupAsync(string personGroupId, string name)
 {
     await faceClient.CreatePersonGroupAsync(personGroupId, name);
 }
Ejemplo n.º 19
0
        public async Task CreateTenantAsync(string name, string groupId)
        {
            await faceServiceClient.CreatePersonGroupAsync(groupId, name);

            RegisterTenant(name, groupId);
        }
Ejemplo n.º 20
0
        static async Task SetupFaceVerification(string personGroupId)
        {
            try
            {
                bool groupExists  = false;
                var  personGroups = await _faceServiceClient.ListPersonGroupsAsync();

                foreach (PersonGroup personGroup in personGroups)
                {
                    if (personGroup.PersonGroupId == personGroupId)
                    {
                        groupExists = true;
                    }
                }
                if (!groupExists)
                {
                    await _faceServiceClient.CreatePersonGroupAsync(personGroupId, "All Employees");

                    _dadId = await CreatePerson(personGroupId, "John");

                    _momId = await CreatePerson(personGroupId, "Samantha");

                    _daughterId = await CreatePerson(personGroupId, "Natasha");

                    string imageDir = @"C:\Dev\GitHub\Cognitive-Face-Windows\Data\PersonGroup\Family1-Dad\";
                    await DetectFacesAndAddtoPerson(imageDir, personGroupId, _dadId);

                    imageDir = @"C:\Dev\GitHub\Cognitive-Face-Windows\Data\PersonGroup\Family1-Mom\";
                    await DetectFacesAndAddtoPerson(imageDir, personGroupId, _momId);

                    imageDir = @"C:\Dev\GitHub\Cognitive-Face-Windows\Data\PersonGroup\Family1-Daughter\";
                    await DetectFacesAndAddtoPerson(imageDir, personGroupId, _daughterId);

                    await _faceServiceClient.TrainPersonGroupAsync(personGroupId);

                    while (true)
                    {
                        TrainingStatus trainingStatus = null;
                        try
                        {
                            trainingStatus = await _faceServiceClient.GetPersonGroupTrainingStatusAsync(personGroupId);

                            Console.WriteLine("...Train status: CreatedDateTime: " + trainingStatus.CreatedDateTime + ", Status:" + trainingStatus.Status);

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

                            await Task.Delay(1000);
                        }
                        catch (FaceAPIException ex)
                        {
                            Console.WriteLine(ex.ErrorCode);
                            Console.WriteLine(ex.ErrorMessage);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("That PersonGroup already exists, skipping setup...");
                }
            }
            catch (FaceAPIException oops)
            {
                Console.WriteLine(oops.ErrorCode);
                Console.WriteLine(oops.ErrorMessage);

                // Since it's just a poc...
                throw;
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Create a Person Group with ID and name provided if none can be found in the service.
        /// </summary>
        /// <param name="sender">A sender object</param>
        /// <param name="e">RoutedEventArgs</param>
        /// <remarks>
        /// <para>Method for creating a new person group. Must create a group to work with Persons</para>
        /// </remarks>
        private async void CreatePersonGroupButton_ClickAsync(object sender, RoutedEventArgs e)
        {
            //Clear Globals
            personGroupId   = PersonGroupIdTextBox.Text;
            personGroupName = PersonGroupNameTextBox.Text;
            authKey         = AuthKeyTextBox.Text;

            //Reset UI Globals
            PersonStatusTextBlock.Text         = "";
            UpdateUserDataStatusTextBlock.Text = "";
            SubmissionStatusTextBlock.Text     = "";
            TrainStatusTextBlock.Text          = "";

            //Reset UI Colors
            PersonStatusTextBlock.Foreground         = new SolidColorBrush(Colors.Black);
            UpdateUserDataStatusTextBlock.Foreground = new SolidColorBrush(Colors.Black);
            SubmissionStatusTextBlock.Foreground     = new SolidColorBrush(Colors.Black);
            TrainStatusTextBlock.Foreground          = new SolidColorBrush(Colors.Black);
            PersonGroupStatusTextBlock.Foreground    = new SolidColorBrush(Colors.Black);

            //Logic
            if (string.IsNullOrWhiteSpace(personGroupId) == false && string.IsNullOrWhiteSpace(personGroupName) == false && string.IsNullOrWhiteSpace(authKey) == false)
            {
                PersonGroupCreateErrorText.Visibility = Visibility.Collapsed;
                await ApiCallAllowed(true);

                faceServiceClient = new FaceServiceClient(authKey);

                if (null != faceServiceClient)
                {
                    // You may experience issues with this below call, if you are attempting connection with
                    // a service location other than 'West US'
                    PersonGroup[] groups = await faceServiceClient.ListPersonGroupsAsync();

                    var matchedGroups = groups.Where(p => p.PersonGroupId == personGroupId);

                    if (matchedGroups.Count() > 0)
                    {
                        knownGroup = matchedGroups.FirstOrDefault();

                        PersonGroupStatusTextBlock.Text = "Found existing: " + knownGroup.Name;
                    }

                    if (null == knownGroup)
                    {
                        await ApiCallAllowed(true);

                        await faceServiceClient.CreatePersonGroupAsync(personGroupId, personGroupName);

                        knownGroup = await faceServiceClient.GetPersonGroupAsync(personGroupId);

                        PersonGroupStatusTextBlock.Text = "Created new group: " + knownGroup.Name;
                    }

                    if (PersonGroupStatusTextBlock.Text != "- Person Group status -")
                    {
                        PersonGroupStatusTextBlock.Foreground = new SolidColorBrush(Colors.Green);
                    }
                    else
                    {
                        PersonGroupStatusTextBlock.Foreground = new SolidColorBrush(Colors.Red);
                    }
                }
            }
            else
            {
                PersonGroupCreateErrorText.Text       = "Make sure you provide: a Person Group ID, a Person Group Name, and the Authentication Key in the section above.";
                PersonGroupCreateErrorText.Visibility = Visibility.Visible;
            }
        }
 public async Task CreatePersonGroup(string personGroupId, string groupName)
 {
     await _faceServiceClient.CreatePersonGroupAsync(personGroupId.ToLower(), groupName);
 }
Ejemplo n.º 23
0
        // PUT: api/Uploadphoto/5
        public static async void Put(string facebookID, string fileDir)
        {
            bool groupExists       = false;
            var  faceServiceClient = new FaceServiceClient(subscriptionKey);

            try
            {
                //MainWindow.Log("Request: Group {0} will be used for build person database. Checking whether group exists.", GroupName);

                await faceServiceClient.GetPersonGroupAsync(GroupName);

                groupExists = true;
                //MainWindow.Log("Response: Group {0} exists.", GroupName);
            }
            catch (FaceAPIException ex)
            {
                if (ex.ErrorCode != "PersonGroupNotFound")
                {
                    //MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                    return;
                }
                else
                {
                    //MainWindow.Log("Response: Group {0} does not exist before.", GroupName);
                }
            }
            if (!groupExists)
            {
                //MainWindow.Log("Request: Creating group \"{0}\"", GroupName);
                try
                {
                    await faceServiceClient.CreatePersonGroupAsync(GroupName, GroupName);

                    //MainWindow.Log("Response: Success. Group \"{0}\" created", GroupName);
                }
                catch (FaceAPIException ex)
                {
                    //MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                    return;
                }
            }
            var    tag         = facebookID;
            var    faces       = new ObservableCollection <Face>();
            string personName  = tag;
            string personID    = (await faceServiceClient.CreatePersonAsync(GroupName, personName)).PersonId.ToString();
            var    fStream     = File.OpenRead(fileDir);
            var    persistFace = await faceServiceClient.AddPersonFaceAsync(GroupName, Guid.Parse(personID), fStream, fileDir);

            //return new Tuple<string, ClientContract.AddPersistedFaceResult>(value, persistFace);
            //await Task.WhenAll(tasks);
            try
            {
                // Start train person group
                //MainWindow.Log("Request: Training group \"{0}\"", GroupName);
                await faceServiceClient.TrainPersonGroupAsync(GroupName);

                // Wait until train completed
                while (true)
                {
                    await Task.Delay(1000);

                    var status = await faceServiceClient.GetPersonGroupTrainingStatusAsync(GroupName);

                    Console.WriteLine("Response: {0}. Group \"{1}\" training process is {2}", "Success", GroupName, status.Status);
                    if (status.Status != (Status)2)
                    {
                        break;
                    }
                }
            }
            catch (FaceAPIException ex)
            {
                //MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
            }
        }
        /// <summary>
        /// Pick image folder to detect faces and using these faces to create the person database
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void PersonImageFolderPicker_Click(object sender, RoutedEventArgs e)
        {
            bool groupExists = false;

            MainWindow mainWindow      = Window.GetWindow(this) as MainWindow;
            string     subscriptionKey = mainWindow._scenariosControl.SubscriptionKey;

            var faceServiceClient = new FaceServiceClient(subscriptionKey);

            // Test whether the group already exists
            try
            {
                MainWindow.Log("Request: Group {0} will be used to build a person database. Checking whether the group exists.", GroupName);

                await faceServiceClient.GetPersonGroupAsync(GroupName);

                groupExists = true;
                MainWindow.Log("Response: Group {0} exists.", GroupName);
            }
            catch (FaceAPIException ex)
            {
                if (ex.ErrorCode != "PersonGroupNotFound")
                {
                    MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                    return;
                }
                else
                {
                    MainWindow.Log("Response: Group {0} did not exist previously.", GroupName);
                }
            }

            if (groupExists)
            {
                var cleanGroup = System.Windows.MessageBox.Show(string.Format("Requires a clean up for group \"{0}\" before setting up a new person database. Click OK to proceed, group \"{0}\" will be cleared.", GroupName), "Warning", MessageBoxButton.OKCancel);
                if (cleanGroup == MessageBoxResult.OK)
                {
                    await faceServiceClient.DeletePersonGroupAsync(GroupName);

                    PersonVerifyResult = string.Empty;
                    Person.Faces.Clear();
                }
                else
                {
                    return;
                }
            }

            // Show folder picker
            System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
            var result = dlg.ShowDialog();

            // Set the suggestion count is intent to minimum the data preparation step only,
            // it's not corresponding to service side constraint
            const int SuggestionCount = 15;

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                FacesCollection.Clear();
                PersonVerifyButton.IsEnabled = (FacesCollection.Count != 0 && RightFaceResultCollection.Count != 0);

                // Call create person group REST API
                // Create person group API call will failed if group with the same name already exists
                MainWindow.Log("Request: Creating group \"{0}\"", GroupName);
                try
                {
                    await faceServiceClient.CreatePersonGroupAsync(GroupName, GroupName);

                    MainWindow.Log("Response: Success. Group \"{0}\" created", GroupName);
                }
                catch (FaceAPIException ex)
                {
                    MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                    return;
                }

                int  processCount  = 0;
                bool forceContinue = false;

                MainWindow.Log("Request: Preparing person for verification, detecting faces in chosen folder.");

                // Enumerate top level directories, each directory contains one person's images

                var tasks = new List <Task>();
                var tag   = System.IO.Path.GetFileName(dlg.SelectedPath);
                Person            = new Person();
                Person.PersonName = tag;

                var faces = new ObservableCollection <Face>();
                Person.Faces = faces;

                // Call create person REST API, the new create person id will be returned
                MainWindow.Log("Request: Creating person \"{0}\"", Person.PersonName);
                Person.PersonId =
                    (await faceServiceClient.CreatePersonAsync(GroupName, Person.PersonName)).PersonId.ToString();
                MainWindow.Log("Response: Success. Person \"{0}\" (PersonID:{1}) created", Person.PersonName, Person.PersonId);

                string img;
                var    imageList =
                    new ConcurrentBag <string>(
                        Directory.EnumerateFiles(dlg.SelectedPath, "*.*", SearchOption.AllDirectories)
                        .Where(s => s.EndsWith(".jpg") || s.EndsWith(".png") || s.EndsWith(".bmp") || s.EndsWith(".gif")));

                // Enumerate images under the person folder, call detection
                int invalidImageCount = 0;
                while (imageList.TryTake(out img))
                {
                    tasks.Add(Task.Factory.StartNew(
                                  async(obj) =>
                    {
                        var imgPath = obj as string;

                        using (var fStream = File.OpenRead(imgPath))
                        {
                            try
                            {
                                var persistFace =
                                    await
                                    faceServiceClient.AddPersonFaceAsync(GroupName, Guid.Parse(Person.PersonId),
                                                                         fStream, imgPath);
                                return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath,
                                                                                                 persistFace));
                            }
                            catch (FaceAPIException ex)
                            {
                                // if operation conflict, retry.
                                if (ex.ErrorCode.Equals("ConcurrentOperationConflict"))
                                {
                                    imageList.Add(imgPath);
                                    return(null);
                                }
                                // if operation cause rate limit exceed, retry.
                                else if (ex.ErrorCode.Equals("RateLimitExceeded"))
                                {
                                    imageList.Add(imgPath);
                                    return(null);
                                }
                                else if (ex.ErrorMessage.Contains("more than 1 face in the image."))
                                {
                                    Interlocked.Increment(ref invalidImageCount);
                                }
                                // Here we simply ignore all detection failure in this sample
                                // You may handle these exceptions by check the Error.Error.Code and Error.Message property for ClientException object
                                return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, null));
                            }
                        }
                    },
                                  img).Unwrap().ContinueWith((detectTask) =>
                    {
                        // Update detected faces for rendering
                        var detectionResult = detectTask?.Result;
                        if (detectionResult?.Item2 == null)
                        {
                            return;
                        }

                        this.Dispatcher.Invoke(
                            new Action
                            <ObservableCollection <Face>, string, ClientContract.AddPersistedFaceResult>(
                                UIHelper.UpdateFace),
                            FacesCollection,
                            detectionResult.Item1,
                            detectionResult.Item2);
                    }));
                    processCount++;

                    if (processCount >= SuggestionCount && !forceContinue)
                    {
                        var continueProcess =
                            System.Windows.Forms.MessageBox.Show(
                                "The images loaded have reached the recommended count, may take long time if proceed. Would you like to continue to load images?",
                                "Warning", System.Windows.Forms.MessageBoxButtons.YesNo);
                        if (continueProcess == System.Windows.Forms.DialogResult.Yes)
                        {
                            forceContinue = true;
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (tasks.Count >= _maxConcurrentProcesses || imageList.IsEmpty)
                    {
                        await Task.WhenAll(tasks);

                        tasks.Clear();
                    }
                }

                Person.Faces = FacesCollection;

                PersonVerifyButton.IsEnabled = (FacesCollection.Count != 0 && RightFaceResultCollection.Count != 0);

                if (invalidImageCount > 0)
                {
                    MainWindow.Log("Warning: more or less than one face is detected in {0} images, can not add to face list.", invalidImageCount);
                }
                MainWindow.Log("Response: Success. Total {0} faces are detected.", Person.Faces.Count);
            }
            GC.Collect();
        }
Ejemplo n.º 25
0
        private async void StartButton_Click(object sender, RoutedEventArgs e)
        {
            if (!CameraList.HasItems)
            {
                MessageArea.Text = "No cameras found; cannot start processing";
                return;
            }

            // Clean leading/trailing spaces in API keys.
            Properties.Settings.Default.FaceAPIKey    = Properties.Settings.Default.FaceAPIKey.Trim();
            Properties.Settings.Default.EmotionAPIKey = Properties.Settings.Default.EmotionAPIKey.Trim();
            Properties.Settings.Default.VisionAPIKey  = Properties.Settings.Default.VisionAPIKey.Trim();

            // Create API clients.
            _faceClient = new FaceServiceClient(Properties.Settings.Default.FaceAPIKey, Properties.Settings.Default.FaceAPIHost);
            //_faceClient = new FaceServiceClient("5d017c9a97c745c6a1e45c2a8edaec95", "https://southcentralus.api.cognitive.microsoft.com/face/v1.0");

            _emotionClient = new EmotionServiceClient(Properties.Settings.Default.EmotionAPIKey, Properties.Settings.Default.EmotionAPIHost);
            _visionClient  = new VisionServiceClient(Properties.Settings.Default.VisionAPIKey, Properties.Settings.Default.VisionAPIHost);

            // How often to analyze.
            _grabber.TriggerAnalysisOnInterval(Properties.Settings.Default.AnalysisInterval);

            // Reset message.
            MessageArea.Text = "";

            // Record start time, for auto-stop
            _startTime = DateTime.Now;

            // Process IP Cam
            if (CameraList.SelectedIndex == CameraList.Items.Count - 1)
            {
                await _grabber.StartProcessingCameraAsync(-1, Properties.Settings.Default.IPCamURL);
            }
            else
            {
                await _grabber.StartProcessingCameraAsync(CameraList.SelectedIndex);
            }


            //Windana

            _groupId = Properties.Settings.Default.FaceApiGroup;
            try
            {
                await _faceClient.GetPersonGroupAsync(_groupId);
            }
            catch
            {
                try
                {
                    await _faceClient.DeletePersonGroupAsync(_groupId);

                    await _faceClient.CreatePersonGroupAsync(_groupId, _groupId);
                }
                catch (Exception ex)
                {
                    BotClient_OnResponse(ex.Message, MessageType.Metadata);
                }
            }
            //End Windana
        }
Ejemplo n.º 26
0
        async static Task registerPerson(string faceAPIKey,
                                         string faceAPIRegion,
                                         string personGroupId,
                                         string personName,
                                         string personImageFolderPath)
        {
            Console.WriteLine("  Connect Face API");
            var faceServiceClient =
                new FaceServiceClient(faceAPIKey,
                                      $"https://{faceAPIRegion}.api.cognitive.microsoft.com/face/v1.0");

            Console.WriteLine("  Create | Get Person Group");
            try
            {
                await faceServiceClient.DeletePersonGroupAsync(personGroupId);

                var presonGroup = await faceServiceClient.GetPersonGroupAsync(personGroupId);
            } catch (FaceAPIException e)
            {
                if (e.ErrorCode == "PersonGroupNotFound")
                {
                    Console.WriteLine("  Create Person Group");
                    await faceServiceClient.CreatePersonGroupAsync(personGroupId, personGroupId);
                }
                else
                {
                    Console.WriteLine($"  Exception - GetPersonGroupAsync: {e.Message}");
                    return;
                }
            }

            Console.WriteLine("  Add Person");
            CreatePersonResult friend1 = await faceServiceClient.CreatePersonAsync(
                personGroupId,
                personName
                );

            Console.WriteLine("  Add Images to Person");
            foreach (string imagePath in Directory.GetFiles(personImageFolderPath, "*.jpg")
                     .Concat(Directory.GetFiles(personImageFolderPath, "*.png"))
                     .Concat(Directory.GetFiles(personImageFolderPath, "*.gif"))
                     .Concat(Directory.GetFiles(personImageFolderPath, "*.bmp"))
                     .ToArray())
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    // Detect faces in the image and add to Anna
                    await faceServiceClient.AddPersonFaceAsync(
                        personGroupId, friend1.PersonId, s);
                }
            }

            Console.WriteLine("  Start training to Person Group");
            await faceServiceClient.TrainPersonGroupAsync(personGroupId);

            TrainingStatus trainingStatus = null;

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

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

                await Task.Delay(1000);
            }
        }
 public async Task CreateGroup()
 {
     await _client.CreatePersonGroupAsync("users_id", "users");
 }
Ejemplo n.º 28
0
        private async void GroupTest()
        {
            var photodir = await KnownFolders.PicturesLibrary.GetFileAsync(PHOTO_FILE_NAME);

            string photo = photodir.Path;

            string picdir = photo.Substring(0, photo.Length - 9);



            try
            {
                await faceServiceClient.CreatePersonGroupAsync(personGroupId, "FaceGroup");


                //tbl_status.Text = "Group created";
            }
            catch
            {
                //tbl_status.Text = "Group exists";
            }

            try
            {
                var persons = await faceServiceClient.ListPersonsAsync(personGroupId);

                foreach (var person in persons)
                {
                    if (person.PersistedFaceIds.Count() == 0)
                    {
                        personlist.Add(person.PersonId.ToString());
                    }
                }
                var lists = personlist;
                for (int i = 0; i < personlist.Count; i++)
                {
                    await faceServiceClient.DeletePersonAsync(personGroupId, Guid.Parse(personlist[i]));
                }
                await faceServiceClient.TrainPersonGroupAsync(personGroupId);

                TrainingStatus trainingStatus = null;
                while (true)
                {
                    trainingStatus = await faceServiceClient.GetPersonGroupTrainingStatusAsync(personGroupId);

                    if (trainingStatus.Status.ToString() != "running")
                    {
                        break;
                    }

                    await Task.Delay(1000);
                }


                string testImageFile = photo;



                using (Stream s = File.OpenRead(await GetPhoto()))
                {
                    var faces = await faceServiceClient.DetectAsync(s, returnFaceLandmarks : true,
                                                                    returnFaceAttributes : requiredFaceAttributes);

                    foreach (var faceinfo in faces)
                    {
                        var id          = faceinfo.FaceId;
                        var attributes  = faceinfo.FaceAttributes;
                        var age         = attributes.Age;
                        var gender      = attributes.Gender;
                        var smile       = attributes.Smile;
                        var facialHair  = attributes.FacialHair;
                        var headPose    = attributes.HeadPose;
                        var glasses     = attributes.Glasses;
                        var emotion     = attributes.Emotion;
                        var emotionlist = emotion;
                        int i           = 0;
                        int max         = 0;

                        /*foreach (var kvp in emotionlist.ToRankedList())
                         * {
                         *  if(kvp.Value > max)
                         *  {
                         *      maxemotion = i;
                         *  }
                         *  object[] item = new object[2];
                         *  item[0] = kvp.Key;
                         *  item[1] = kvp.Value;
                         *  i++;
                         * }
                         * Infostring = "Mood: " + list[maxemotion][0].ToString();*/
                        // emo = emotionlist.Max().Value;
                        // emotionstring = emotion.Happiness.ToString();
                        if (glasses.ToString().ToUpper() != "NOGLASSES")
                        {
                            activeId += " Gleraugnaglámur";
                        }
                        Infostring = "ID: " + id.ToString() + "," + "Age: " + age.ToString() + "," + "Gender: " + gender.ToString() + "," + "Glasses: " + glasses.ToString();
                    }

                    //emo.ToString();

                    var faceIds = faces.Select(face => face.FaceId).ToArray();
                    var results = await faceServiceClient.IdentifyAsync(personGroupId, faceIds);


                    foreach (var identifyResult in results)
                    {
                        //  tbl_status.Text = ("Result of face: " + identifyResult.FaceId);
                        if (identifyResult.Candidates.Length == 0)
                        {
                            //tbl_status.Text = ("No one identified, i will add you now, your new name is Bill");
                            CreatePersonResult friend1 = await faceServiceClient.CreatePersonAsync(
                                // Id of the person group that the person belonged to
                                personGroupId,
                                // Name of the person
                                "Hlini"
                                );

                            for (int z = 0; z < 6; z++)
                            {
                                Random r = new Random();
                                photostorage = await KnownFolders.PicturesLibrary.CreateFileAsync((z + PHOTO_FILE_NAME), CreationCollisionOption.ReplaceExisting);

                                ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
                                await mediaCapture.CapturePhotoToStorageFileAsync(imageProperties, photostorage);

                                var friend1ImageDir = await KnownFolders.PicturesLibrary.GetFileAsync(z + PHOTO_FILE_NAME);

                                string imagePath = friend1ImageDir.Path;

                                using (Stream k = File.OpenRead(imagePath))
                                {
                                    await faceServiceClient.AddPersonFaceAsync(
                                        personGroupId, friend1.PersonId, k);
                                }
                            }


                            await faceServiceClient.TrainPersonGroupAsync(personGroupId);

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

                                if (trainingStatus.Status.ToString() != "running")
                                {
                                    break;
                                }

                                await Task.Delay(1000);
                            }
                            Task t = Task.Run(() => { CheckFace(); });
                        }
                        else
                        {
                            // Get top 1 among all candidates returned
                            var candidateId = identifyResult.Candidates[0].PersonId;
                            var person      = await faceServiceClient.GetPersonAsync(personGroupId, candidateId);

                            //tbl_status.Text = ("Identified as " + person.Name);
                            //activeId = person.Name.ToString();
                            //await faceServiceClient.UpdatePersonAsync(personGroupId, person.PersonId, "Ólafur Jón");
                            activeId = person.Name.ToString();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                activeId = "Main: " + activeId + " " + Infostring;
            }
        }
Ejemplo n.º 29
0
        private async Task LoadPersonGroup()
        {
            bool groupExists = false;

            _faceClient = new FaceServiceClient(Properties.Settings.Default.FaceAPIKey.Trim(), Properties.Settings.Default.FaceAPIHost);
            try
            {
                await _faceClient.GetPersonGroupAsync(GroupName);

                groupExists = true;
            }
            catch (FaceAPIException ex)
            {
                if (ex.ErrorCode != "PersonGroupNotFound")
                {
                    return;
                }
            }

            if (groupExists)
            {
                await _faceClient.DeletePersonGroupAsync(GroupName);
            }

            try
            {
                await _faceClient.CreatePersonGroupAsync(GroupName, GroupName);
            }
            catch (FaceAPIException ex)
            {
                return;
            }

            int invalidImageCount = 0;

            foreach (var dir in System.IO.Directory.EnumerateDirectories(@"D:\Hackathon_Live_Project\exit0\source\app\LiveCameraSample\Data\PersonGroup"))
            {
                var             tasks = new List <Task>();
                var             tag   = System.IO.Path.GetFileName(dir);
                PersonViewModel p     = new PersonViewModel();
                p.PersonName = tag;

                var faces = new ObservableCollection <FaceViewModel>();
                p.Faces = faces;

                p.PersonId = (await _faceClient.CreatePersonAsync(GroupName, p.PersonName)).PersonId.ToString();
                var pName = p.PersonName.Split('-');
                listOfNames.Add(p.PersonId, new UserDetails()
                {
                    UserName = pName[1].ToString(), ZoomId = pName[2].ToString()
                });

                string img;
                // Enumerate images under the person folder, call detection
                var imageList =
                    new ConcurrentBag <string>(
                        Directory.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories)
                        .Where(s => s.ToLower().EndsWith(".jpg") || s.ToLower().EndsWith(".png") || s.ToLower().EndsWith(".bmp") || s.ToLower().EndsWith(".gif")));

                while (imageList.TryTake(out img))
                {
                    tasks.Add(Task.Factory.StartNew(
                                  async(obj) =>
                    {
                        var imgPath = obj as string;

                        using (var fStream = File.OpenRead(imgPath))
                        {
                            try
                            {
                                // Update person faces on server side
                                var persistFace = await _faceClient.AddPersonFaceAsync(GroupName, Guid.Parse(p.PersonId), fStream, imgPath);
                                return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, persistFace));
                            }
                            catch (FaceAPIException ex)
                            {
                                // if operation conflict, retry.
                                if (ex.ErrorCode.Equals("ConcurrentOperationConflict"))
                                {
                                    imageList.Add(imgPath);
                                    return(null);
                                }
                                // if operation cause rate limit exceed, retry.
                                else if (ex.ErrorCode.Equals("RateLimitExceeded"))
                                {
                                    imageList.Add(imgPath);
                                    return(null);
                                }
                                else if (ex.ErrorMessage.Contains("more than 1 face in the image."))
                                {
                                    Interlocked.Increment(ref invalidImageCount);
                                }
                                // Here we simply ignore all detection failure in this sample
                                // You may handle these exceptions by check the Error.Error.Code and Error.Message property for ClientException object
                                return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, null));
                            }
                        }
                    },
                                  img).Unwrap().ContinueWith(async(detectTask) =>
                    {
                        // Update detected faces for rendering
                        var detectionResult = detectTask?.Result;
                        if (detectionResult == null || detectionResult.Item2 == null)
                        {
                            return;
                        }

                        if (tasks.Count >= _maxConcurrentProcesses || imageList.IsEmpty)
                        {
                            await Task.WhenAll(tasks);
                            tasks.Clear();
                        }
                    }));

                    Persons.Add(p);
                }
                try
                {
                    await _faceClient.TrainPersonGroupAsync(GroupName);

                    // Wait until train completed
                    while (true)
                    {
                        await Task.Delay(2000);

                        var status = await _faceClient.GetPersonGroupTrainingStatusAsync(GroupName);

                        if (status.Status != Microsoft.ProjectOxford.Face.Contract.Status.Running)
                        {
                            break;
                        }
                    }
                }
                catch (FaceAPIException ex)
                {
                }
            }
            GC.Collect();
        }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            //Input oxfordKey
            Console.WriteLine("Please input the OxfordPrimaryKey: ");
            string            oxfordProjectKey = Console.ReadLine();
            FaceServiceClient faceClient       = new FaceServiceClient(oxfordProjectKey);

            //Create PersonGroup
            string groupName = "";
            string groupId   = "";

            Console.WriteLine("Create a new Person Group? [Y/N]");
            string personGroupChoice = Console.ReadLine();

            if (personGroupChoice == "Y")
            {
                Console.WriteLine("Please input the PersonGroup Name: ");
                groupName = Console.ReadLine();
                groupId   = Guid.NewGuid().ToString();
                var runSync = Task.Factory.StartNew(new Func <Task>(async() =>
                {
                    await faceClient.CreatePersonGroupAsync(groupId, groupName);
                })).Unwrap();
                runSync.Wait();
            }
            else
            {
                Console.WriteLine("Please input the PersonGroup Id: ");
                groupId = Console.ReadLine();
            }

            Console.WriteLine("Adding person and his photos......");
            //Add Persons and Photos
            DirectoryInfo        dirPrograms = new DirectoryInfo(Environment.CurrentDirectory);
            List <DirectoryInfo> dirs        = new List <DirectoryInfo>(dirPrograms.EnumerateDirectories());

            foreach (DirectoryInfo dirsplit in dirs)
            {
                string lastName  = dirsplit.Name.Substring(dirsplit.Name.IndexOf("_") + 1, dirsplit.Name.Length - dirsplit.Name.IndexOf("_") - 1);
                string firstName = dirsplit.Name.Substring(0, dirsplit.Name.IndexOf("_"));
                //Create Person
                CreatePersonResult personResult = null;
                var runSync = Task.Factory.StartNew(new Func <Task>(async() =>
                {
                    personResult = await faceClient.CreatePersonAsync(groupId, firstName + " " + lastName);
                })).Unwrap();
                runSync.Wait();
                Console.WriteLine("Creating " + firstName + " " + lastName);
                //Add photos
                List <FileInfo> files = new List <FileInfo>(dirsplit.EnumerateFiles());
                foreach (FileInfo filesplit in files)
                {
                    FileStream fs0   = new FileStream(filesplit.Directory + "\\" + filesplit.Name, FileMode.Open);
                    byte[]     bytes = new byte[fs0.Length];
                    fs0.Read(bytes, 0, bytes.Length);
                    fs0.Close();
                    Stream imageStream = new MemoryStream(bytes);
                    AddPersistedFaceResult perFaceResult = null;
                    runSync = Task.Factory.StartNew(new Func <Task>(async() =>
                    {
                        perFaceResult = await faceClient.AddPersonFaceAsync(groupId, personResult.PersonId, imageStream);
                    })).Unwrap();
                    runSync.Wait();
                }
            }

            //Train and get training status
            faceClient.TrainPersonGroupAsync(groupId);
            TrainingStatus trStatus = null;

            do
            {
                Console.WriteLine("Waiting for training.");
                Thread.Sleep(3000);
                var runSync = Task.Factory.StartNew(new Func <Task>(async() =>
                {
                    trStatus = await faceClient.GetPersonGroupTrainingStatusAsync(groupId);
                })).Unwrap();
                runSync.Wait();
            } while (trStatus == null || trStatus.Status == Status.Running);

            Console.WriteLine("TrainingStatus: " + trStatus.Status.ToString());

            //Write the info to txt file
            string       data1 = "oxfordKey: " + oxfordProjectKey;
            string       data2 = "PersonGroupId: " + groupId;
            StreamWriter sw    = new StreamWriter("OxfordData.txt", false, Encoding.Default);

            sw.WriteLine(data1);
            sw.WriteLine(data2);
            sw.Close();

            Console.ReadLine();
        }
Ejemplo n.º 31
0
        private async void button_Click(object sender, RoutedEventArgs e)
        {
            if (button_mode == "startGame")
            {
                button.Content = "Start Again";
                button_mode    = "restartGame";
                var    otherJpg    = lastFrame.Image.Clone().ToMemoryStream(".jpg", s_jpegParams);
                byte[] streamBytes = ReadFully(otherJpg);

                this.sound = SoundProvider.PrepareYourself;
                this.sound.Play();
                this.gameState            = GameState.Explain;
                this.currentTimerTask     = TimeSpan.FromSeconds(12);
                this.currentTimeTaskStart = DateTime.Now;
                button.Visibility         = Visibility.Hidden;
                this.currentTimeTaskStart = DateTime.Now;

                //FaceServiceClient faceClient = new FaceServiceClient("3b6c7018fa594441b2465d5d8652526a", "https://westeurope.api.cognitive.microsoft.com/face/v1.0");
                await _faceClient.CreatePersonGroupAsync(currentGroupId, currentGroupName);

                Face[]      clonedCurrentParticipants = (Face[])currentParticipants.Clone();
                List <Guid> personids = new List <Guid>();
                if (clonedCurrentParticipants.Length > 1)
                {
                    var bitmap = lastFrame.Image.ToBitmapSource();
                    for (int i = 0; i < clonedCurrentParticipants.Length; i++)
                    {
                        CreatePersonResult person = await _faceClient.CreatePersonAsync(currentGroupId, i.ToString());

                        personids.Add(person.PersonId);
                        MemoryStream  s            = new MemoryStream(streamBytes);
                        var           rect         = clonedCurrentParticipants[i].FaceRectangle;
                        var           int32Rect    = new Int32Rect(rect.Left, rect.Top, rect.Width, rect.Height);
                        CroppedBitmap playerBitmap = new CroppedBitmap(bitmap, int32Rect);
                        playerImages[person.PersonId] = new List <CroppedBitmap>();
                        playerImages[person.PersonId].Add(playerBitmap);
                        var addedPersistedPerson = await _faceClient.AddPersonFaceAsync(currentGroupId, person.PersonId, s, "userData", clonedCurrentParticipants[i].FaceRectangle);
                    }
                    scoringSystem = new ScoringSystem(personids.ToArray());
                    await _faceClient.TrainPersonGroupAsync(currentGroupId);
                }
            }
            else if (button_mode == "restartGame")
            {
                currentGroupId   = Guid.NewGuid().ToString();
                roundsPlayed     = new HashSet <EmotionType>();
                currentGroupName = currentGroupId;
                roundNumber      = 0;
                t.Stop();
                groupImages  = new List <BitmapSource>();
                playerImages = new Dictionary <Guid, List <CroppedBitmap> >();
                this.Dispatcher.BeginInvoke((Action)(() =>
                {
                    button.Content = "Start Game";
                    button.Visibility = Visibility.Hidden;
                    this.gameState = GameState.Participants;
                    button_mode = "startGame";
                    updateMode(AppMode.Participants);
                    _grabber.StartProcessingCameraAsync(0);
                }));
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Pick the root person database folder, to minimum the data preparation logic, the folder should be under following construction
        /// Each person's image should be put into one folder named as the person's name
        /// All person's image folder should be put directly under the root person database folder
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event argument</param>
        public async void Load()
        {
            bool groupExists = false;

            // Test whether the group already exists
            try
            {
                await FaceServiceClient.GetPersonGroupAsync(GroupName);

                groupExists = true;
            }
            catch (FaceAPIException ex)
            {
                if (ex.ErrorCode != "PersonGroupNotFound")
                {
                    MainWindow.LoaderStatusLabel.Content = "Error";
                    return;
                }
            }

            // If group exists, warn user it will be replaced
            if (groupExists)
            {
                var cleanGroup = System.Windows.MessageBox.Show(string.Format("Requires a clean up for group \"{0}\" before setting up a new person database. Click OK to proceed, group \"{0}\" will be cleared.", GroupName), "Warning", MessageBoxButton.OKCancel);
                if (cleanGroup == MessageBoxResult.OK)
                {
                    MainWindow.LoaderStatusLabel.Content = "Removing Group";
                    await FaceServiceClient.DeletePersonGroupAsync(GroupName);
                }
                else
                {
                    return;
                }
            }

            // Show folder picker
            System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
            var result = dlg.ShowDialog();

            // Set the suggestion count is intent to minimum the data preparation step only,
            // it's not corresponding to service side constraint
            const int SuggestionCount = 15;

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                // User picked a root person database folder

                // Call create person group REST API
                // Create person group API call will failed if group with the same name already exists
                MainWindow.LoaderStatusLabel.Content = "Creating Group";
                try
                {
                    await FaceServiceClient.CreatePersonGroupAsync(GroupName, GroupName);

                    MainWindow.LoaderStatusLabel.Content = "Group Created";
                }
                catch (FaceAPIException)
                {
                    MainWindow.LoaderStatusLabel.Content = "Error";
                    return;
                }

                int  processCount  = 0;
                bool forceContinue = false;

                MainWindow.LoaderStatusLabel.Content = "Processing images";

                // Enumerate top level directories, each directory contains one person's images
                int invalidImageCount = 0;
                foreach (var dir in System.IO.Directory.EnumerateDirectories(dlg.SelectedPath))
                {
                    var tasks      = new List <Task>();
                    var tag        = System.IO.Path.GetFileName(dir);
                    var personName = tag;
                    var faces      = new ObservableCollection <Face>();

                    // Call create person REST API, the new create person id will be returned
                    var personId = (await FaceServiceClient.CreatePersonAsync(GroupName, personName)).PersonId.ToString();

                    string img;
                    // Enumerate images under the person folder, call detection
                    var imageList = new ConcurrentBag <string>(
                        Directory.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories)
                        .Where(s => s.ToLower().EndsWith(".jpg") || s.ToLower().EndsWith(".png") || s.ToLower().EndsWith(".bmp") || s.ToLower().EndsWith(".gif")));

                    while (imageList.TryTake(out img))
                    {
                        tasks.Add(Task.Factory.StartNew(
                                      async(obj) =>
                        {
                            var imgPath = obj as string;

                            using (var fStream = File.OpenRead(imgPath))
                            {
                                try
                                {
                                    // Update person faces on server side
                                    var persistFace = await FaceServiceClient.AddPersonFaceAsync(GroupName, Guid.Parse(personId), fStream, imgPath);
                                    return(new Tuple <string, Microsoft.ProjectOxford.Face.Contract.AddPersistedFaceResult>(imgPath, persistFace));
                                }
                                catch (FaceAPIException ex)
                                {
                                    // if operation conflict, retry.
                                    if (ex.ErrorCode.Equals("ConcurrentOperationConflict"))
                                    {
                                        imageList.Add(imgPath);
                                        return(null);
                                    }
                                    // if operation cause rate limit exceed, retry.
                                    else if (ex.ErrorCode.Equals("RateLimitExceeded"))
                                    {
                                        imageList.Add(imgPath);
                                        return(null);
                                    }
                                    else if (ex.ErrorMessage.Contains("more than 1 face in the image."))
                                    {
                                        Interlocked.Increment(ref invalidImageCount);
                                    }
                                    // Here we simply ignore all detection failure in this sample
                                    // You may handle these exceptions by check the Error.Error.Code and Error.Message property for ClientException object
                                    return(new Tuple <string, Microsoft.ProjectOxford.Face.Contract.AddPersistedFaceResult>(imgPath, null));
                                }
                            }
                        },
                                      img).Unwrap());

                        if (processCount >= SuggestionCount && !forceContinue)
                        {
                            var continueProcess = System.Windows.Forms.MessageBox.Show("The images loaded have reached the recommended count, may take long time if proceed. Would you like to continue to load images?", "Warning", System.Windows.Forms.MessageBoxButtons.YesNo);
                            if (continueProcess == System.Windows.Forms.DialogResult.Yes)
                            {
                                forceContinue = true;
                            }
                            else
                            {
                                break;
                            }
                        }

                        if (tasks.Count >= _maxConcurrentProcesses || imageList.IsEmpty)
                        {
                            await Task.WhenAll(tasks);

                            tasks.Clear();
                        }
                    }
                }

                try
                {
                    // Start train person group
                    MainWindow.LoaderStatusLabel.Content = "Training Person Group";
                    await FaceServiceClient.TrainPersonGroupAsync(GroupName);

                    // Wait until train completed
                    while (true)
                    {
                        await Task.Delay(1000);

                        var status = await FaceServiceClient.GetPersonGroupTrainingStatusAsync(GroupName);

                        if (status.Status != Microsoft.ProjectOxford.Face.Contract.Status.Running)
                        {
                            break;
                        }
                    }
                }
                catch (FaceAPIException)
                {
                    MainWindow.LoaderStatusLabel.Content = "Error";
                }
            }
            MainWindow.LoaderStatusLabel.Content = "Done";
            GC.Collect();
        }