コード例 #1
0
ファイル: FaceClient.cs プロジェクト: jwkuper/Mobile3
        public async Task ResetFaceGroups()
        {
            try
            {
                var groups = await Service.ListPersonGroupsAsync();

                foreach (var group in groups)
                {
                    await Service.DeletePersonGroupAsync(group.PersonGroupId);
                }

                await Service.CreatePersonGroupAsync(LoyalCustomerGroup, LoyalCustomerGroup);

                await Service.CreatePersonGroupAsync(AnonymousCustomerGroup, AnonymousCustomerGroup);
            }
            catch (FaceAPIException ex)
            {
                switch (ex.ErrorCode)
                {
                case "BadArgument":
                    break;

                default:
                    break;
                }
                //errorDescription = "IdentifyFace: " + ex.ErrorCode;
                //currentLog.Info(errorDescription);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #2
0
        private async static void DeletePersonGroups()
        {
            Console.WriteLine("Enter the Person Group Id");
            string personGroupId = Console.ReadLine();
            await _faceServiceClient.DeletePersonGroupAsync(personGroupId);

            Console.WriteLine($"Finished Deleting the person group: {personGroupId}");
        }
コード例 #3
0
        /// <summary>
        /// 刪除人員群組的動作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnDeletePersonGroup_Click(object sender, EventArgs e)
        {
            string strPersonGroupId = ((Models.CognitiveModels.ListItem)lbxPersonGroup.SelectedItem).Value;
            await face.DeletePersonGroupAsync(strPersonGroupId);

            this.BindPersonGroups();
            btnDeletePersonGroup.Enabled = false;
            btnPersonGroupTrain.Enabled  = false;
            btnAddPerson.Enabled         = false;
        }
コード例 #4
0
        private static async Task DeleteGroup(FaceServiceClient faceServiceClient)
        {
            try
            {
                await faceServiceClient.DeletePersonGroupAsync(Constants.PERSON_GROUP_ID);

                Console.WriteLine("Group deleted succesfully");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
コード例 #5
0
        public async Task <string> deletePersonGroup(string personGroupId)
        {
            try
            {
                await faceServiceClient.DeletePersonGroupAsync(personGroupId);

                return("Deleted personGroup ");
            }
            catch (Exception ex)
            {
                return("Delete error");
            }
        }
コード例 #6
0
 public void DeleteGroup(PersonGroup group)
 {
     if (group != null)
     {
         try
         {
             Task.Run(() => Api.DeletePersonGroupAsync(group.Name.ToLowerInvariant())).GetAwaiter().GetResult();
         }
         catch (FaceAPIException ex)
         {
             throw new FaceApiException(ex.ErrorMessage);
         }
     }
 }
コード例 #7
0
        private async void CreatePersonsAndTrain()
        {
            var path = @"c:\training\richard\";

            // Create an empty PersonGroup
            try {
                await faceApi.DeletePersonGroupAsync(personGroupId);
            }
            catch { }
            await faceApi.CreatePersonGroupAsync(personGroupId, personGroupId);

            // Define Anna
            CreatePersonResult friend1 = await faceApi.CreatePersonAsync(
                // Id of the PersonGroup that the person belonged to
                personGroupId,
                // Name of the person
                "Richard"
                );

            // Directory contains image files of Richard
            string friend1ImageDir = path;

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

            // Train the myfamily group
            await faceApi.TrainPersonGroupAsync(personGroupId);

            TrainingStatus trainingStatus = null;

            while (true)
            {
                Console.WriteLine("Training...");
                trainingStatus = await faceApi.GetPersonGroupTrainingStatusAsync(personGroupId);

                if (trainingStatus.Status != Status.Running)
                {
                    Console.WriteLine("Done!");
                    break;
                }

                await Task.Delay(1000);
            }
        }
        private async void DeletePersonGroup(object obj)
        {
            try
            {
                await _faceServiceClient.DeletePersonGroupAsync(SelectedPersonGroup.PersonGroupId);

                StatusText = $"Deleted person group {SelectedPersonGroup.Name}";

                GetPersonGroups();
            }
            catch (FaceAPIException ex)
            {
                StatusText = $"Could not delete person group {SelectedPersonGroup.Name}: {ex.ErrorMessage}";
            }
            catch (Exception ex)
            {
                StatusText = $"Could not delete person group {SelectedPersonGroup.Name}: {ex.Message}";
            }
        }
コード例 #9
0
        /// <summary>
        /// 全ての学習を忘却する。
        /// </summary>
        /// <param name="senderId">LINE Messagin Service の SenderId</param>
        public async Task ForgetAllAsync(string senderId)
        {
            var personGroupId = SenderIdToPersonGroupId(senderId);

            // 対象の PersonGroup を探す。見つからなければ何もしない。
            var personGroup = await FindPersonGroupBySenderIdAsync(senderId);

            if (personGroup == null)
            {
                return;
            }

            // Cognitive Face 上の PersonGroup を削除
            await _faceServiceClient.DeletePersonGroupAsync(personGroupId);

            // データベース上の Person と PersonGroup を削除
            _db.Person.RemoveRange(_db.Person.Where(p => p.PersonGroupId == personGroupId).ToList());
            _db.PersonGroup.Remove(personGroup);
            await _db.SaveChangesAsync();
        }
コード例 #10
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;
            }



        }
コード例 #11
0
        private async void MainWindow_OnLoaded(object sender, RoutedEventArgs args)
        {
            // Here we train the cognitive Service endpoint
            try
            {
                try
                {
                    // Delete previously created PersonGroup
                    await _faceServiceClient.DeletePersonGroupAsync(PersonGroupId);
                }
                catch
                {
                    // Ignored
                }

                // Create the PersonGroup
                await _faceServiceClient.CreatePersonGroupAsync(PersonGroupId, PersonGroupName);

                foreach (var imagePath in Directory.GetFiles(@"../../Assets/CrewPhotos", "*.jpg"))
                {
                    var member = CrewRepository.FromPhoto(Path.GetFileName(imagePath));
                    // Create the Person
                    var personResult = await _faceServiceClient.CreatePersonAsync(PersonGroupId, name : member.Name);

                    using (Stream s = File.OpenRead(imagePath))
                    {
                        // Add the Person to the Group
                        await _faceServiceClient.AddPersonFaceAsync(PersonGroupId, personResult.PersonId, s);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
            finally
            {
                IdentifyButton.IsEnabled = true;
                ProgressGrid.Visibility  = Visibility.Collapsed;
            }
        }
コード例 #12
0
        static async void DeletePersonGroup(FaceServiceClient faceCli)
        {
            inputMode = false;

            var groups = await faceCli.ListPersonGroupsAsync();



            foreach (var group in groups)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Group Id: " + group.PersonGroupId);
                Console.ForegroundColor = ConsoleColor.Gray;
            }


            Console.WriteLine("");
            Console.WriteLine("Enter the name of person you wish to delete: ");
            string personGroupId = Console.ReadLine();

            try
            {
                await faceCli.DeletePersonGroupAsync(personGroupId);

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Group : " + personGroupId + " successfully deleted");
                Console.ForegroundColor = ConsoleColor.Gray;
                inputMode = true;
                paintMenu();
            }
            catch (FaceAPIException ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.ErrorMessage);
                Console.ForegroundColor = ConsoleColor.Gray;
                inputMode = true;
                paintMenu();
            }
        }
コード例 #13
0
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("Into Page_Loaded");

            // Init Face Service Client
            faceServiceClient = new FaceServiceClient(AppConstants.FaceApiSubscriptionKey,
                                                      AppConstants.FaceServicesBaseUrl);

            // Clean-up possible PersonGroup objects (including persons attached to them)
            try
            {
                var pgList = await faceServiceClient.ListPersonGroupsAsync();

                foreach (var pg in pgList)
                {
                    await faceServiceClient.DeletePersonGroupAsync(pg.PersonGroupId);
                }

                // Init PersonGroup
                Debug.WriteLine($"Initializing Person Group: {PersonGroup}");

                await faceServiceClient.CreatePersonGroupAsync(PersonGroup, PersonGroup);

                BtnInitCam.IsEnabled = true;
            }
            catch (FaceAPIException ex)
            {
                Debug.WriteLine($"Error deleting old PersonGroup objects: {ex.ErrorMessage}");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Exception in Page_Loaded: {ex.Message}");
            }

            Debug.WriteLine("Out of: Page_Loaded");
        }
コード例 #14
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();
        }
コード例 #15
0
 public async Task DeletePersonGroup(string personGroupId)
 {
     await faceServiceClient.DeletePersonGroupAsync(personGroupId);
 }
コード例 #16
0
 public void DeletePersonGroup(string personGroupId)
 {
     _fsClient.DeletePersonGroupAsync(personGroupId);
 }
コード例 #17
0
 static async void DeleteEverything(string personGroupId)
 {
     await _faceServiceClient.DeletePersonGroupAsync(personGroupId);
 }
コード例 #18
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");
        }
コード例 #19
0
 public async Task DeletePersonGroup(string id)
 {
     await FaceServiceClient.DeletePersonGroupAsync(id);
 }
コード例 #20
0
        /// <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();
        }
コード例 #21
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
        }
コード例 #22
0
 public async Task DeleteGroup()
 {
     await ServiceClient.DeletePersonGroupAsync(GroupId);
 }
コード例 #23
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);
            }
        }
コード例 #24
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>
        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);
                }
            }
        }
コード例 #25
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>
        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);
                }
            }
        }
コード例 #26
0
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                speechSynthesizer.Rate = -2;
                speechSynthesizer.SpeakAsync("Hi Visitor, Welcome to the new world of NCR.");
                await Task.Delay(1000);

                speechSynthesizer.SpeakAsync("To verify your face. Please put your face clearly infront of the ATM.");
                //DeleteSpeaker();
                await UpdateAllSpeakersAsync();

                //DeleteEnrollment(Guid.Parse("b6dc2382-1657-4ffe-9092-f98a28509573"));
                SpeakerIdentificationServiceClient _serviceClient = new SpeakerIdentificationServiceClient(speakerAPISubscriptionKey);

                bool groupExists = false;

                var faceServiceClient = new FaceServiceClient(faceAPISubscriptionKey);
                // Test whether the group already exists
                try
                {
                    Title = String.Format("Request: Group {0} will be used to build a person database. Checking whether the group exists.", GroupName);
                    Console.WriteLine("Request: Group {0} will be used to build a person database. Checking whether the group exists.", GroupName);

                    await faceServiceClient.GetPersonGroupAsync(GroupName);

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

                if (groupExists)
                {
                    var cleanGroup = 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);
                    }
                    else
                    {
                        return;
                    }
                }

                Title = String.Format("Request: Creating group \"{0}\"", GroupName);
                try
                {
                    await faceServiceClient.CreatePersonGroupAsync(GroupName, GroupName);

                    Title = String.Format("Response: Success. Group \"{0}\" created", GroupName);
                }
                catch (FaceAPIException ex)
                {
                    Title = String.Format("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                    return;
                }
                //DeleteSpeaker();
                //DeleteEnrollment(Guid.Parse("b6dc2382-1657-4ffe-9092-f98a28509573"));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error : ", ex.Message);
            }
        }
コード例 #27
0
ファイル: MainWindow.xaml.cs プロジェクト: vjaindmi/exit0
        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();
        }
コード例 #28
0
ファイル: FaceApiService.cs プロジェクト: JHinW/OpgWebApi
 public async Task DeletePersonGroupAsync(string personGroupId)
 {
     await RunTaskWithAutoRetryOnQuotaLimitExceededError(() => faceClient.DeletePersonGroupAsync(personGroupId));
 }
コード例 #29
0
ファイル: MainForm.cs プロジェクト: FixedBuffer/AzureFaceAPI
        private async void btn_Train_Click(object sender, EventArgs e)
        {
            //Abrimos un dialogo de seleccion de carpetas
            FolderBrowserDialog dialog = new FolderBrowserDialog();

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                //Si se ha seleccionado un directorio, hacemos su info
                DirectoryInfo directory = new DirectoryInfo(dialog.SelectedPath);

                //Comprobamos que el directorio tiene carpetas de personas
                if (directory.GetDirectories().Count() == 0)
                {
                    return;
                }

                //=====Empezamos a crear el grupo de trabajo
                //Creamos el cliente
                var faceServiceClient = new FaceServiceClient(FaceAPIKey, FaceAPIEndPoint);

                //Vamos a trabajar desde 0 siempre, asi que comprobamos si hay grupos, y si los hay los borramos
                var groups = await faceServiceClient.ListPersonGroupsAsync();

                foreach (var group in groups)
                {
                    await faceServiceClient.DeletePersonGroupAsync(group.PersonGroupId);
                }
                //Creamos un grupo
                await faceServiceClient.CreatePersonGroupAsync(GroupGUID, "FixedBuffer");

                foreach (var person in directory.GetDirectories())
                {
                    //Comprobamos que tenga imagenes
                    if (person.GetFiles().Count() == 0)
                    {
                        return;
                    }

                    //Obtenemos el nombre que le vamos a dar a la persona
                    var personName = person.Name;

                    lbl_Status.Text = $"Entrenando a {personName}";

                    //Añadimos a una persona al grupo
                    var personResult = await faceServiceClient.CreatePersonAsync(GroupGUID, personName);

                    //Añadimos todas las fotos a la persona
                    foreach (var file in person.GetFiles())
                    {
                        using (var fStream = File.OpenRead(file.FullName))
                        {
                            try
                            {
                                //Cargamos la imagen en el pictureBox
                                pct_Imagen.Image = new Bitmap(fStream);
                                //Reiniciamos el Stream
                                fStream.Seek(0, SeekOrigin.Begin);
                                // Actualizamos las caras en el servidor
                                var persistFace = await faceServiceClient.AddPersonFaceInPersonGroupAsync(GroupGUID, personResult.PersonId, fStream, file.FullName);
                            }
                            catch (FaceAPIException ex)
                            {
                                lbl_Status.Text = "";
                                MessageBox.Show($"Imposible seguir, razón:{ex.ErrorMessage}");
                                return;
                            }
                        }
                    }
                }

                try
                {
                    //Entrenamos el grupo con todas las personas que hemos metido
                    await faceServiceClient.TrainPersonGroupAsync(GroupGUID);

                    // Esperamos a que el entrenamiento acabe
                    while (true)
                    {
                        await Task.Delay(1000);

                        var status = await faceServiceClient.GetPersonGroupTrainingStatusAsync(GroupGUID);

                        if (status.Status != Microsoft.ProjectOxford.Face.Contract.Status.Running)
                        {
                            break;
                        }
                    }

                    //Si hemos llegado hasta aqui, el entrenamiento se ha completado
                    btn_Find.Enabled = true;
                    lbl_Status.Text  = $"Entrenamiento completado";
                }
                catch (FaceAPIException ex)
                {
                    lbl_Status.Text = "";
                    MessageBox.Show($"Response: {ex.ErrorCode}. {ex.ErrorMessage}");
                }
                GC.Collect();
            }
        }