Example #1
0
        /// <summary>
        /// Pick image and call find similar for each faces detected
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private async void FindSimilar_Click(object sender, RoutedEventArgs e)
        {
            // Show file picker
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".jpg";
            dlg.Filter     = "Image files(*.jpg) | *.jpg";
            var filePicker = dlg.ShowDialog();

            if (filePicker.HasValue && filePicker.Value)
            {
                // User picked image
                // Clear previous detection and find similar results
                TargetFaces.Clear();
                FindSimilarCollection.Clear();

                var sw = Stopwatch.StartNew();
                SelectedFile = dlg.FileName;

                var imageInfo = UIHelper.GetImageInfoForRendering(SelectedFile);

                // Detect all faces in the picked image
                using (var fileStream = File.OpenRead(SelectedFile))
                {
                    MainWindow.Log("Request: Detecting faces in {0}", SelectedFile);

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

                    var faceServiceClient = new FaceServiceClient(subscriptionKey);
                    var faces             = await faceServiceClient.DetectAsync(fileStream);

                    // Update detected faces on UI
                    foreach (var face in UIHelper.CalculateFaceRectangleForRendering(faces, MaxImageSize, imageInfo))
                    {
                        TargetFaces.Add(face);
                    }

                    MainWindow.Log("Response: Success. Detected {0} face(s) in {0}", faces.Length, SelectedFile);

                    // Find similar faces for each face
                    foreach (var f in faces)
                    {
                        var faceId = f.FaceId;

                        MainWindow.Log("Request: Finding similar faces for face {0}", faceId);

                        try
                        {
                            // Call find similar REST API, the result contains all the face ids which similar to the query face
                            const int requestCandidatesCount = 3;
                            var       result = await faceServiceClient.FindSimilarAsync(faceId, _faceListName, requestCandidatesCount);

                            // Update find similar results collection for rendering
                            var gg = new FindSimilarResult();
                            gg.Faces     = new ObservableCollection <Face>();
                            gg.QueryFace = new Face()
                            {
                                ImagePath = SelectedFile,
                                Top       = f.FaceRectangle.Top,
                                Left      = f.FaceRectangle.Left,
                                Width     = f.FaceRectangle.Width,
                                Height    = f.FaceRectangle.Height,
                                FaceId    = faceId.ToString(),
                            };
                            foreach (var fr in result)
                            {
                                gg.Faces.Add(FacesCollection.First(ff => ff.FaceId == fr.PersistedFaceId.ToString()));
                            }

                            MainWindow.Log("Response: Found {0} similar faces for face {1}", gg.Faces.Count, faceId);

                            FindSimilarCollection.Add(gg);
                        }
                        catch (FaceAPIException ex)
                        {
                            MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                        }
                    }
                }
            }
        }
Example #2
0
        /// <summary>
        /// Pick image folder and detect all faces in these images
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private async void FolderPicker_Click(object sender, RoutedEventArgs e)
        {
            // Show folder picker
            System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
            var result = dlg.ShowDialog();

            bool forceContinue = false;

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                // Enumerate all ".jpg" files in the folder, call detect
                List <Task> tasks = new List <Task>();

                FacesCollection.Clear();
                TargetFaces.Clear();
                FindSimilarCollection.Clear();
                SelectedFile = null;

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

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

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

                var faceServiceClient = new FaceServiceClient(subscriptionKey);

                _faceListName = Guid.NewGuid().ToString();
                await faceServiceClient.CreateFaceListAsync(_faceListName, _faceListName, "face list for sample");

                foreach (var img in Directory.EnumerateFiles(dlg.SelectedPath, "*.jpg", SearchOption.AllDirectories))
                {
                    tasks.Add(Task.Factory.StartNew(
                                  async(obj) =>
                    {
                        var imgPath = obj as string;

                        // Call detection
                        using (var fStream = File.OpenRead(imgPath))
                        {
                            try
                            {
                                var faces = await faceServiceClient.AddFaceToFaceListAsync(_faceListName, fStream);
                                return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, faces));
                            }
                            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) =>
                    {
                        var res = detectTask.Result;
                        if (res.Item2 == null)
                        {
                            return;
                        }

                        // Update detected faces on UI
                        this.Dispatcher.Invoke(
                            new Action <ObservableCollection <Face>, string, ClientContract.AddPersistedFaceResult>(UIHelper.UpdateFace),
                            FacesCollection,
                            res.Item1,
                            res.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;
                        }
                    }
                }

                await Task.WhenAll(tasks);

                MainWindow.Log("Response: Success. Total {0} faces are detected.", FacesCollection.Count);
            }
        }
Example #3
0
        /// <summary>
        /// Pick image and call find similar for each faces detected
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private async void FindSimilar_Click(object sender, RoutedEventArgs e)
        {
            // Show file picker
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".jpg";
            dlg.Filter     = "Image files(*.jpg) | *.jpg";
            var filePicker = dlg.ShowDialog();

            if (filePicker.HasValue && filePicker.Value)
            {
                // User picked image
                // Clear previous detection and find similar results
                TargetFaces.Clear();
                FindSimilarCollection.Clear();

                var sw = Stopwatch.StartNew();
                SelectedFile = dlg.FileName;

                var imageInfo = UIHelper.GetImageInfoForRendering(SelectedFile);

                // Detect all faces in the picked image
                using (var fileStream = File.OpenRead(SelectedFile))
                {
                    Output = Output.AppendLine(string.Format("Request: Detecting faces in {0}", SelectedFile));

                    var faces = await App.Instance.DetectAsync(fileStream);

                    // Update detected faces on UI
                    foreach (var face in UIHelper.CalculateFaceRectangleForRendering(faces, MaxImageSize, imageInfo))
                    {
                        TargetFaces.Add(face);
                    }

                    Output = Output.AppendLine(string.Format("Response: Success. Detected {0} face(s) in {0}", faces.Length, SelectedFile));

                    // Find similar faces for each face
                    foreach (var f in faces)
                    {
                        var faceId = f.FaceId;

                        Output = Output.AppendLine(string.Format("Request: Finding similar faces for face {0}", faceId));

                        try
                        {
                            // Call find similar REST API, the result contains all the face ids which similar to the query face
                            var result = await App.Instance.FindSimilarAsync(faceId, FacesCollection.Select(ff => Guid.Parse(ff.FaceId)).ToArray());

                            // Update find similar results collection for rendering
                            var gg = new FindSimilarResult();
                            gg.Faces     = new ObservableCollection <Face>();
                            gg.QueryFace = new Face()
                            {
                                ImagePath = SelectedFile,
                                Top       = f.FaceRectangle.Top,
                                Left      = f.FaceRectangle.Left,
                                Width     = f.FaceRectangle.Width,
                                Height    = f.FaceRectangle.Height,
                                FaceId    = faceId.ToString(),
                            };
                            foreach (var fr in result)
                            {
                                gg.Faces.Add(FacesCollection.First(ff => ff.FaceId == fr.FaceId.ToString()));
                            }

                            Output = Output.AppendLine(string.Format("Response: Found {0} similar faces for face {1}", gg.Faces.Count, faceId));

                            FindSimilarCollection.Add(gg);
                        }
                        catch (ClientException ex)
                        {
                            Output = Output.AppendLine(string.Format("Response: {0}. {1}", ex.Error.Code, ex.Error.Message));
                        }
                    }
                }
            }
        }