Beispiel #1
0
        public async Task <bool> UpsertFaceListAndCheckIfContainsFaceAsync()
        {
            try
            {
                var faceListIdIn = faceListId.ToString();
                var faceLists    = await _faceServiceClient.ListFaceListsAsync();

                var faceList = faceLists.FirstOrDefault(_ => _.FaceListId == faceListIdIn);

                if (faceList == null)
                {
                    await _faceServiceClient.CreateFaceListAsync(faceListIdIn, "GeekBurgerFaces", null);

                    return(false);
                }

                var faceListJustCreated = await _faceServiceClient.GetFaceListAsync(faceListIdIn);

                return(faceListJustCreated.PersistedFaces.Any());
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        private static async Task <bool> UpsertFaceListAndCheckIfContainsFaceAsync()
        {
            try
            {
                faceServiceClient = new FaceServiceClient(Configuration["FaceAPIKey"], "https://eastus.api.cognitive.microsoft.com/face/v1.0");
                var faceListId = Guid.Parse(Configuration["FaceListId"]).ToString();
                var faceLists  = await faceServiceClient.ListFaceListsAsync();

                var faceList = faceLists.FirstOrDefault(_ => _.FaceListId == FaceListId.ToString());

                if (faceList == null)
                {
                    await faceServiceClient.CreateFaceListAsync(faceListId, "GeekBurgerFaces", null);

                    return(false);
                }

                var faceListJustCreated = await faceServiceClient.GetFaceListAsync(faceListId);

                return(faceListJustCreated.PersistedFaces.Any());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #3
0
        /// <summary>
        /// Function to update the list of Face IDs, based on the example images added
        /// </summary>
        private async void UpdateFaceGuidsAsync()
        {
            if (!_faceListExists)
            {
                return;
            }

            try
            {
                FaceList faceList = await _faceServiceClient.GetFaceListAsync(FaceListName.ToLower());

                if (faceList == null)
                {
                    return;
                }

                PersistedFace[] faces = faceList.PersistedFaces;

                foreach (PersistedFace face in faces)
                {
                    FaceIds.Add(face.PersistedFaceId);
                }
            }
            catch (FaceAPIException ex)
            {
                Debug.WriteLine($"Failed to get face list - {ex.ErrorMessage}");
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Beispiel #4
0
        public async Task RegisterFaceAsync(string faceId, ImageRequest request)
        {
            var client = new FaceServiceClient(subscriptionKey: Secrets.CongnitiveServiceFaceApiKey, apiRoot: Consts.CognitiveServiceFaceApiEndPoint);

            try
            {
                await client.GetFaceListAsync(faceId);
            }
            catch (FaceAPIException)
            {
                // not found
                await client.CreateFaceListAsync(faceListId : faceId, name : faceId);
            }

            await client.AddFaceToFaceListAsync(faceListId : faceId, imageStream : new MemoryStream(request.Image));
        }
        private async Task <bool> UpsertFaceListAndCheckIfContainsFaceAsync()
        {
            var faceLists = await _faceServiceClient.ListFaceListsAsync();

            var faceList = faceLists.FirstOrDefault(_ => _.FaceListId == _faceListId);

            if (faceList == null)
            {
                await _faceServiceClient.CreateFaceListAsync(_faceListId, "geekburger-users-face", null);

                return(false);
            }

            var faceListJustCreated = await _faceServiceClient.GetFaceListAsync(_faceListId);

            return(faceListJustCreated.PersistedFaces.Any());
        }
Beispiel #6
0
        private static async Task <bool> UpsertFaceListAndCheckIfContainsFaceAsync()
        {
            var faceListId = FaceListId.ToString();
            var faceLists  = await faceServiceClient.ListFaceListsAsync();

            var faceList = faceLists.FirstOrDefault(_ => _.FaceListId == FaceListId.ToString());

            if (faceList == null)
            {
                await faceServiceClient.CreateFaceListAsync(faceListId, "GeekBurgerFaces", null);

                return(false);
            }

            var faceListJustCreated = await faceServiceClient.GetFaceListAsync(faceListId);

            return(faceListJustCreated.PersistedFaces.Any());
        }
Beispiel #7
0
 /// <summary>
 /// 根据facelisId获取其相关信息
 /// </summary>
 /// <param name="listId">FaceListId</param>
 /// <returns></returns>
 public async Task <FaceList> GetFaceListInfoById(string listId)
 {
     return(await faceServiceClient.GetFaceListAsync(listId));
 }
Beispiel #8
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)
        {
            bool groupExists = false;

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

            var faceServiceClient = new FaceServiceClient(subscriptionKey);

            try
            {
                MainWindow.Log("Request: Face List {0} will be used to build a person database. Checking whether the face list exists.", _faceListName);

                await faceServiceClient.GetFaceListAsync(_faceListName);

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

            if (groupExists)
            {
                var cleanFaceList = System.Windows.MessageBox.Show(string.Format("Requires a clean up for face list \"{0}\" before setting up a new face list. Click OK to proceed, face list \"{0}\" will be cleared.", _faceListName), "Warning", MessageBoxButton.OKCancel);
                if (cleanFaceList == MessageBoxResult.OK)
                {
                    await faceServiceClient.DeleteFaceListAsync(_faceListName);
                }
                else
                {
                    return;
                }
            }

            OpenFaceButton.IsEnabled = false;
            // 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();
                FindSimilarMatchPersonCollection.Clear();
                FindSimilarMatchFaceCollection.Clear();
                SelectedFile = null;

                // Set the suggestion count is intent to minimum the data preparation 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.");

                await faceServiceClient.CreateFaceListAsync(_faceListName, _faceListName, "face list for sample");

                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")));

                string img;
                int    invalidImageCount = 0;
                while (imageList.TryTake(out img))
                {
                    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 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) =>
                    {
                        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;
                        }
                    }

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

                        tasks.Clear();
                    }
                }
                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.", FacesCollection.Count);
            }
            GC.Collect();
            OpenFaceButton.IsEnabled = true;
        }
        private async void FaceBox_Click(object sender, RoutedEventArgs e)
        {
            var faceButton = (Button)sender;
            var faceServiceClient = new FaceServiceClient(_subscriptionKey);
            var faceLists = await faceServiceClient.ListFaceListsAsync();
            var faceList = faceLists.First(fl => fl.Name.StartsWith(_faceListNameRoot));
            var fl2 = await faceServiceClient.GetFaceListAsync(faceList.FaceListId);
            var similarFaces = await faceServiceClient.FindSimilarAsync(new Guid(faceButton.Tag.ToString()), faceList.FaceListId);

            SimilarFaces.ItemsSource = from pf in fl2.PersistedFaces
                                       join sf in similarFaces
                                       on pf.PersistedFaceId equals sf.PersistedFaceId
                                       orderby sf.Confidence descending
                                       select new SimilarFaceResult(pf.UserData)
                                       {
                                           Confidence = (int)(sf.Confidence * 100)
                                       };

        }
 private async void RefreshFaceLists(object sender, RoutedEventArgs e)
 {
     var faceServiceClient = new FaceServiceClient(_subscriptionKey);
     var facelists = await faceServiceClient.ListFaceListsAsync();
     foreach (var facelist in facelists)
     {
         if (facelist.FaceListId.StartsWith(_faceListNameRoot))
         {
             var faceListData = new FaceListData { FaceListId = facelist.FaceListId };
             var fl = await faceServiceClient.GetFaceListAsync(facelist.FaceListId);
             faceListData.PersistedFaces = fl.PersistedFaces.Count();
             _faceLists.Add(faceListData);
         }
     }
 }
Beispiel #11
0
        async Task <AiResult> MakeRequest(string imageToCheck)
        {
            AiResult res = new AiResult();
            // imageToCheck = "https://www.liberationnews.org/wp-content/uploads/2015/07/donaldtrump61815.jpg";

            EmotionServiceClient emotionServiceClient = new EmotionServiceClient(emotionKey);

            Emotion[] imageEmotion = await emotionServiceClient.RecognizeAsync(imageToCheck);

            Console.WriteLine("Feeling: " + imageEmotion[0].Scores.ToRankedList().First().Key);
            Console.WriteLine("Top score: " + imageEmotion[0].Scores.ToRankedList().First().Value);

            res.Emotion = string.Format("Unknwn ({0:P2})", 0);
            float bestScore = 0;

            foreach (var em in imageEmotion[0].Scores.ToRankedList())
            {
                if (em.Value > bestScore)
                {
                    bestScore   = em.Value;
                    res.Emotion = res.Emotion = string.Format("{0} ({1:P2})", em.Key, em.Value);
                }
            }

            FaceServiceClient faceServiceClient = new FaceServiceClient(faceKey);
            FaceList          trumpList         = null;

            try
            {
                trumpList = await faceServiceClient.GetFaceListAsync(faceList);
            }
            catch (FaceAPIException apiExp)
            {
                if (apiExp.ErrorCode == "FaceListNotFound")
                {
                    await faceServiceClient.CreateFaceListAsync(faceList, faceList, "A collection of trumps");

                    trumpList = await faceServiceClient.GetFaceListAsync(faceList);
                }
                else
                {
                    throw apiExp;
                }
            }
            if (trumpList.PersistedFaces.Count() < 5)
            {
                await faceServiceClient.AddFaceToFaceListAsync(faceList, "https://www.liberationnews.org/wp-content/uploads/2015/07/donaldtrump61815.jpg");

                await faceServiceClient.AddFaceToFaceListAsync(faceList, "http://thefederalist.com/wp-content/uploads/2016/02/trumpie.jpg");

                await faceServiceClient.AddFaceToFaceListAsync(faceList, "http://www.redstate.com/uploads/2016/02/donald-trump-is-still-soaring-in-iowa-but-there-are-now-some-clear-warning-signs.jpg");

                await faceServiceClient.AddFaceToFaceListAsync(faceList, "http://i.huffpost.com/gen/3706868/images/o-DONALD-TRUMP-FUNNY-facebook.jpg");

                await faceServiceClient.AddFaceToFaceListAsync(faceList, "http://media.salon.com/2015/04/donald_trump_thumbsup.jpg");

                trumpList = await faceServiceClient.GetFaceListAsync(faceList);
            }

            Face[] faceToCompare = await faceServiceClient.DetectAsync(imageToCheck);

            SimilarPersistedFace[] faces = await faceServiceClient.FindSimilarAsync(faceToCompare[0].FaceId, faceList, FindSimilarMatchMode.matchFace);

            res.TrumpMatch = String.Format("{0:P2}", 0);
            if (faces.Count() == 0)
            {
                Console.WriteLine("Sorry, nothing compares to you");
            }
            else
            {
                double totalConfidence = 0;
                foreach (SimilarPersistedFace matching in faces)
                {
                    totalConfidence += matching.Confidence;
                }
                double averageConfidence = totalConfidence / faces.Count();
                res.TrumpMatch = String.Format("{0:P2}", averageConfidence);
                Console.WriteLine("Trump comparison: " + res.TrumpMatch);
            }
            return(res);
        }