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.VisionAPIKey = Properties.Settings.Default.VisionAPIKey.Trim();

            // Create API clients.
            //_faceClient = new FaceAPI.FaceServiceClient(Properties.Settings.Default.FaceAPIKey, Properties.Settings.Default.FaceAPIHost);
            //_visionClient = new VisionAPI.VisionServiceClient(Properties.Settings.Default.VisionAPIKey, Properties.Settings.Default.VisionAPIHost);

            _faceClient   = new FaceAPI.FaceServiceClient("3dc9cb73ed524c56a50c77fd4d0f2213", "https://westcentralus.api.cognitive.microsoft.com/face/v1.0");
            _visionClient = new VisionAPI.VisionServiceClient("04429ac7e3dd4adfb9afc09be3296177", "https://westcentralus.api.cognitive.microsoft.com/vision/v1.0");

            // How often to analyze.
            //_grabber.TriggerAnalysisOnInterval(Properties.Settings.Default.AnalysisInterval);
            TimeSpan time = TimeSpan.Parse("00:00:01");

            _grabber.TriggerAnalysisOnInterval(time);

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

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

            await _grabber.StartProcessingCameraAsync(CameraList.SelectedIndex);
        }
Esempio n. 2
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.VisionAPIKey = Properties.Settings.Default.VisionAPIKey.Trim();

            // Create API clients.
            _faceClient   = new FaceAPI.FaceServiceClient(Properties.Settings.Default.FaceAPIKey, Properties.Settings.Default.FaceAPIHost);
            _visionClient = new VisionAPI.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;

            await _grabber.StartProcessingCameraAsync(CameraList.SelectedIndex);
        }
Esempio n. 3
0
        private async void StartButton_Click(object sender, RoutedEventArgs e)
        {
            // Clean leading/trailing spaces in API keys.
            Properties.Settings.Default.FaceAPIKey   = Properties.Settings.Default.FaceAPIKey.Trim();
            Properties.Settings.Default.VisionAPIKey = Properties.Settings.Default.VisionAPIKey.Trim();

            // Create API clients.
            _faceClient   = new FaceAPI.FaceServiceClient(Properties.Settings.Default.FaceAPIKey, Properties.Settings.Default.FaceAPIHost);
            _visionClient = new VisionAPI.VisionServiceClient(Properties.Settings.Default.VisionAPIKey, Properties.Settings.Default.VisionAPIHost);

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


            if (subject_check is true && time_check is true)
            {
                // Reset message.
                MessageArea.Text = "";
                AttendeeList.Items.Clear();
                NoAttendeeList.Items.Clear();
                // Record start time, for auto-stop
                _startTime = DateTime.Now;
                DB_NoAttendeeList();
                // 0번 카메라 실행
                await _grabber.StartProcessingCameraAsync(0);

                //웹캠
                //await _grabber.StartProcessingCameraAsync(1);
            }
        private void CameraThreadStart()
        {
            this.Dispatcher.Invoke(async() =>
            {
                if (!CameraList.HasItems)
                {
                    MessageArea.Text = "No cameras found; cannot start processing";
                    return;
                }

                // Clean leading/trailing spaces in API keys.
                Properties.Settings.Default.FaceAPIKey = ConfigurationManager.AppSettings["FaceAPIKey"].ToString();
                //Properties.Settings.Default.VisionAPIKey = Properties.Settings.Default.VisionAPIKey.Trim();

                // Create API clients.
                _faceClient = new FaceAPI.FaceServiceClient(Properties.Settings.Default.FaceAPIKey, ConfigurationManager.AppSettings["FaceAPIEndPoint"].ToString());
                // _visionClient = new VisionAPI.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;

                await _grabber.StartProcessingCameraAsync(CameraList.SelectedIndex);
            });
        }
Esempio n. 5
0
        private async void StartTracking()
        {
            //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.VisionAPIKey = Properties.Settings.Default.VisionAPIKey.Trim();

            // Create API clients.
            _faceClient   = new FaceAPI.FaceServiceClient(Properties.Settings.Default.FaceAPIKey, Properties.Settings.Default.FaceAPIHost);
            _visionClient = new VisionAPI.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;

            await _grabber.StartProcessingCameraAsync();
        }
Esempio n. 6
0
        /// <summary> Function which submits a frame to the Face API. </summary>
        /// <param name="frame"> The video frame to submit. </param>
        /// <returns> A <see cref="Task{LiveCameraResult}"/> representing the asynchronous API call,
        ///     and containing the faces returned by the API. </returns>
        public async Task UpdatePerson(string personId)
        {
            _faceClient = new FaceAPI.FaceServiceClient(Properties.Settings.Default.FaceAPIKey, Properties.Settings.Default.FaceAPIHost);
            var groups = await _faceClient.ListPersonGroupsAsync();

            foreach (string imagePath in Directory.GetFiles("C:\\Temp\\Pics\\Sabina2"))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    try
                    {
                        var persons = await _faceClient.ListPersonsAsync(_groupId);

                        Person person = persons.Where(pers => pers.Name == personId).FirstOrDefault();
                        Properties.Settings.Default.UploadStatus = String.Format("Updating {0} face: {1}", person.Name, imagePath);

                        await _faceClient.AddPersonFaceAsync(_groupId, person.PersonId, s);
                    }
                    catch (FaceAPIException fae)
                    {
                        Properties.Settings.Default.UploadStatus = "Error: " + fae.Message;
                    }
                }
            }
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            string subscriptionKey = "4c138b4d82b947beb2e2926c92d1e514";
            var    client          = new Microsoft.ProjectOxford.Face.FaceServiceClient(subscriptionKey);

            GetFaces(client);

            Console.ReadLine();
        }
Esempio n. 8
0
        static void Main(string[] args)
        {
            string subscriptionKey = "4c138b4d82b947beb2e2926c92d1e514";
            var client = new Microsoft.ProjectOxford.Face.FaceServiceClient(subscriptionKey);

            GetFaces(client);

            Console.ReadLine();
        }
Esempio n. 9
0
        /// <summary> Function which submits a frame to the Face API. </summary>
        /// <param name="frame"> The video frame to submit. </param>
        /// <returns> A <see cref="Task{LiveCameraResult}"/> representing the asynchronous API call,
        ///     and containing the faces returned by the API. </returns>
        public async Task UploadFaces()
        {
            _faceClient = new FaceAPI.FaceServiceClient(Properties.Settings.Default.FaceAPIKey, Properties.Settings.Default.FaceAPIHost);
            var groups = await _faceClient.ListPersonGroupsAsync();

            var exists = false;

            foreach (var group in groups)
            {
                if (group.PersonGroupId.Equals(_groupId))
                {
                    exists = true;
                    break;
                }
            }
            if (exists)
            {
                var persons = await _faceClient.ListPersonsAsync(_groupId);

                foreach (var person in persons)
                {
                    await _faceClient.DeletePersonAsync(_groupId, person.PersonId);
                }
            }
            else
            {
                await _faceClient.CreatePersonGroupAsync(_groupId, "AtosEmployees");
            }

            var iterator = 0;

            foreach (string dir in Directory.GetDirectories("C:\\Temp\\Pics"))
            {
                var folderName            = dir.Split('\\')[3];
                CreatePersonResult person = await _faceClient.CreatePersonAsync(_groupId, "Person " + iterator ++ + " " + folderName);

                foreach (string imagePath in Directory.GetFiles(dir))
                {
                    using (Stream s = File.OpenRead(imagePath))
                    {
                        try
                        {
                            //await Task.Delay(5000);
                            Properties.Settings.Default.UploadStatus = String.Format("Uploading {0}: {1}", iterator, imagePath);

                            await _faceClient.AddPersonFaceAsync(_groupId, person.PersonId, s);
                        }
                        catch (FaceAPIException fae)
                        {
                            var finishedAt = "";
                        }
                        //await Task.Delay(5000);
                    }
                }
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Checks if the person has been seen before
        /// </summary>
        /// <param name="fId"></param>
        /// <returns></returns>
        public static async Task <bool> CheckIfFaceWasSeenBefore(Guid fId, FaceAPI.FaceServiceClient faceClient, List <Guid> guids)
        {
            if (guids.Count == 0)
            {
                return(false);
            }

            bool retVal = false;

            SimilarFace[] val = await faceClient.FindSimilarAsync(fId, guids.ToArray());

            foreach (SimilarFace similarFace in val)
            {
                if (similarFace.Confidence > 0.4)
                {
                    retVal = true;
                }
            }

            return(retVal);
        }
        private async void StartButton_Click(object sender, RoutedEventArgs e)
        {
            StopButton.Visibility  = Visibility.Visible;
            StartButton.Visibility = Visibility.Collapsed;

            // Create API clients.
            _faceClient   = new FaceAPI.FaceServiceClient(faceApiKey, faceApiHost);
            _visionClient = new VisionAPI.VisionServiceClient(visionApiKey, visionApiHost);

            // How often to analyze.
            _grabber.TriggerAnalysisOnInterval(TimeSpan.FromSeconds(measurementInterval));

            // What to do for analysis
            _grabber.AnalysisFunction = AnalysisFunction;

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

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

            await _grabber.StartProcessingCameraAsync(0);
        }
Esempio n. 12
0
        public async Task <Boolean> StartTraining()
        {
            _faceClient = new FaceAPI.FaceServiceClient(Properties.Settings.Default.FaceAPIKey, Properties.Settings.Default.FaceAPIHost);
            await _faceClient.TrainPersonGroupAsync(_groupId);

            TrainingStatus trainingStatus = null;

            while (true)
            {
                trainingStatus = await _faceClient.GetPersonGroupTrainingStatusAsync(_groupId);

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

                await Task.Delay(1000);
            }

            var persons = await _faceClient.ListPersonsAsync(_groupId);

            return(true);
        }
        public static async Task Train()
        {
            FaceAPI.FaceServiceClient _faceClient = new FaceAPI.FaceServiceClient("952a5cbdd78845948079fe7e2c61807d", "https://australiaeast.api.cognitive.microsoft.com/face/v1.0");

            string personGroupId = "myfriendsServtechAPJ";
            await _faceClient.CreatePersonGroupAsync(personGroupId, "My Friends");

            // Define Jose
            CreatePersonResult Josefriend = await _faceClient.CreatePersonAsync(
                // Id of the PersonGroup that the person belonged to
                personGroupId,
                // Name of the person
                "Jose"
                );

            // Define Jose
            CreatePersonResult Aaronfriend = await _faceClient.CreatePersonAsync(
                // Id of the PersonGroup that the person belonged to
                personGroupId,
                // Name of the person
                "Aaron"
                );

            // Directory contains image files of Anna
            const string JoseImageDir = @"C:\Users\joseo\source\repos\FutureofWork-ServTechAPJ2018\FutureofWork-ServTech2018APJ\LiveCameraSample\Pictures\Jose\";

            foreach (string imagePath in Directory.GetFiles(JoseImageDir, "*.jpg"))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    // Detect faces in the image and add to Anna
                    await _faceClient.AddPersonFaceAsync(
                        personGroupId, Josefriend.PersonId, s);
                }
            }
            // Do the same for Bill and Clare

            const string AaronImageDir = @"C:\Users\joseo\source\repos\FutureofWork-ServTechAPJ2018\FutureofWork-ServTech2018APJ\LiveCameraSample\Pictures\Aaron\";

            foreach (string imagePath in Directory.GetFiles(AaronImageDir, "*.jpg"))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    // Detect faces in the image and add to Anna
                    await _faceClient.AddPersonFaceAsync(
                        personGroupId, Aaronfriend.PersonId, s);
                }
            }
            // Do the same for Bill and Clare


            await _faceClient.TrainPersonGroupAsync(personGroupId);

            FaceAPI.Contract.TrainingStatus trainingStatus = null;
            while (true)
            {
                trainingStatus = await _faceClient.GetPersonGroupTrainingStatusAsync(personGroupId);

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

                await Task.Delay(1000);
            }

            Console.Write("Training successfully completed");
        }
		private async void DetectAsync()
		{
			Shell.SetBusyVisibility( Visibility.Visible, "Taking photo.." );

			this.operationMode = OperationMode.Detect;

			this.viewModel.PhotoFile = await this.camera.CapturePhotoToFileAsync();
			await this.camera.CaptureManager.StopPreviewAsync();

			if( this.led != null )
			{
				this.led.TurnOff();
			}

			Shell.SetBusyVisibility( Visibility.Visible, "Detecting your face.." );
			
			Face.FaceServiceClient faceClient = new Face.FaceServiceClient( FACE_API_KEY );
			Stream stream = await this.viewModel.PhotoFile.OpenStreamForReadAsync();
			Face.Contract.Face[] faces = await faceClient.DetectAsync( stream, analyzesAge: true, analyzesGender: true );

			VoiceGender voiceGender = VoiceGender.Male;
			if( faces.Length == 1 )
			{
				Face.Contract.FaceAttribute face = faces[ 0 ].Attributes;
				string greet;

				if( face.Gender == "male" )
				{
					greet = "Hello Handsome!";
					voiceGender = VoiceGender.Female;
				}
				else
				{
					greet = "Hey, Sexy!";
					voiceGender = VoiceGender.Male;
				}
				this.viewModel.Greet = $"{greet} You look {face.Age} today.";

				await this.SpeakAsync( this.viewModel.Greet, voiceGender, true );
			}
			else
			{
				this.viewModel.Greet = "I cannot see your face :(";
			}

			Shell.SetBusyVisibility( Visibility.Visible, "Detecting your emotions.." );
			
			Emotion.EmotionServiceClient emotionClient = new Emotion.EmotionServiceClient( EMOTION_API_KEY );

			stream = await this.viewModel.PhotoFile.OpenStreamForReadAsync();
			Emotion.Contract.Emotion[] emotions = await emotionClient.RecognizeAsync( stream );
			if( emotions.Length == 1 )
			{
				Emotion.Contract.Scores scores = emotions[ 0 ].Scores;
				this.viewModel.Scores = scores;

				bool like = scores.Happiness > scores.Anger + scores.Sadness + scores.Disgust;

				this.viewModel.EvaluationResult = like
					? "So you liked it! I'm so happy to hear that! :)"
					: "Oh, really? I'm terribly sorry! :(";
				await this.SpeakAsync( this.viewModel.EvaluationResult, voiceGender, false );
			}
			else
			{
				this.viewModel.EvaluationResult = "I cannot see your emotions :(";
			}

			this.operationMode = OperationMode.Done;

			Shell.SetBusyVisibility( Visibility.Collapsed );
		}
Esempio n. 15
0
        private void InitializeClientAPIs()
        {
            // Create API clients.
            _faceClient   = new FaceAPI.FaceServiceClient(FACE_API_KEY, FACE_API_ROOT);
            _visionClient = new VisionAPI.VisionServiceClient(VISION_API_KEY, VISION_API_ROOT);

            _grabber.NewFrameProvided += (s, e) =>
            {
                this.Dispatcher.BeginInvoke((Action)(() =>
                {
                    // Display the image in the left pane captured from camera.
                    LeftImage.Source = e.Frame.Image.ToBitmapSource();
                }));

                // See if auto-stop should be triggered.
                if (Properties.Settings.Default.AutoStopEnabled && (DateTime.Now - _startTime) > Properties.Settings.Default.AutoStopTime)
                {
                    _grabber.StopProcessingAsync();
                }
            };

            // Set up a listener for when the client receives a new result from an API call.
            _grabber.NewResultAvailable += (s, e) =>
            {
                this.Dispatcher.BeginInvoke((Action)(() =>
                {
                    if (e.TimedOut)
                    {
                        MessageArea.Text = "API call timed out.";
                    }
                    else if (e.Exception != null)
                    {
                        string apiName = "";
                        string message = e.Exception.Message;
                        var faceEx = e.Exception as FaceAPI.FaceAPIException;
                        var emotionEx = e.Exception as Common.ClientException;
                        var visionEx = e.Exception as VisionAPI.ClientException;
                        if (faceEx != null)
                        {
                            apiName = "Face";
                            message = faceEx.ErrorMessage;
                        }
                        else if (emotionEx != null)
                        {
                            apiName = "Emotion";
                            message = emotionEx.Error.Message;
                        }
                        else if (visionEx != null)
                        {
                            apiName = "Computer Vision";
                            message = visionEx.Error.Message;
                        }
                        MessageArea.Text = string.Format("{0} API call failed on frame {1}. Exception: {2}", apiName, e.Frame.Metadata.Index, message);
                    }
                    else
                    {
                        if (_mode == AppMode.Text)
                        {
                            if (e.AnalysisResult != null)
                            {
                                foreach (var lr in e.AnalysisResult.Regions)
                                {
                                    if (lr.Lines.Any())
                                    {
                                        StringBuilder builder = new StringBuilder();
                                        foreach (var line in lr.Lines)
                                        {
                                            builder.AppendLine(string.Join(" ", line.Words.Select(w => w.Text).ToArray()));
                                        }

                                        this.Dispatcher.Invoke(() =>
                                        {
                                            ResultList.Items.Add($"Text detected: {builder.ToString()}");
                                        });
                                    }
                                }
                            }
                        }
                        else if (_mode == AppMode.Emotions)
                        {
                            if (e.AnalysisResult != null)
                            {
                                var faces = e.AnalysisResult.EmotionFaces;
                                this.Dispatcher.Invoke(() =>
                                {
                                    foreach (var face in faces)
                                    {
                                        var bestEmotion = face.FaceAttributes.Emotion.ToRankedList().Select(kv => new Tuple <string, float>(kv.Key, kv.Value)).First();
                                        var displayText = string.Format("{0}: {1:N1}", bestEmotion.Item1, bestEmotion.Item2);
                                        ResultList.Items.Add($"Emotion '{displayText}' is detected on face {face.FaceId}.");
                                    }
                                });
                            }
                        }
                        else if (_mode == AppMode.Faces)
                        {
                            if (e.AnalysisResult != null)
                            {
                                var result = e.AnalysisResult.FaceIdentifyResult;
                                this.Dispatcher.Invoke((Action)(() =>
                                {
                                    foreach (var sItem in result)
                                    {
                                        ResultList.Items.Add(sItem);
                                    }
                                }));
                            }
                        }
                    }
                }));
            };

            // Create local face detector.
            _localFaceDetector.Load("Data/haarcascade_frontalface_alt2.xml");
        }
        private async void FolderPicker()
        {
            if (Properties.Settings.Default.FacePath == "path here")
            {
                return;
            }
            _faceClient = new FaceAPI.FaceServiceClient(Properties.Settings.Default.FaceAPIKey, Properties.Settings.Default.FaceAPIHost);
            bool groupExists = false;

            MainWindow mainWindow        = System.Windows.Window.GetWindow(this) as MainWindow;
            var        faceServiceClient = _faceClient;

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

                await faceServiceClient.GetLargePersonGroupAsync(this.GroupId);

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



            // 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 (Properties.Settings.Default.FacePath != "path here")
            {
                // User picked a root person database folder
                // Clear person database
                Persons.Clear();
                TargetFaces.Clear();
                SelectedFile = null;
                //IdentifyButton.IsEnabled = false;

                // Call create large person group REST API
                // Create large person group API call will failed if group with the same name already exists
                if (groupExists)
                {
                    Log("Request: Loading group \"{0}\"", this.GroupId);
                    load_Persons = await faceServiceClient.ListPersonsInLargePersonGroupAsync(this.GroupId);
                }
                else
                {
                    Log("Request: Creating group \"{0}\"", this.GroupId);
                    try {
                        await faceServiceClient.CreateLargePersonGroupAsync(this.GroupId, this.GroupId);

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


                int  processCount  = 0;
                bool forceContinue = false;

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

                // Enumerate top level directories, each directory contains one person's images
                int invalidImageCount = 0;
                personData.Clear();

                int i = 0;
                foreach (var dir in System.IO.Directory.EnumerateDirectories(Properties.Settings.Default.FacePath))
                {
                    i++;
                }
                imageWall.Init(i);
                i = 0;
                foreach (var dir in System.IO.Directory.EnumerateDirectories(Properties.Settings.Default.FacePath))
                {
                    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
                    Log("Request: Creating person \"{0}\"", p.PersonName);

                    Guid personid = Guid.NewGuid();
                    bool isFound  = false;
                    if (groupExists)
                    {
                        isFound = FindPersonByName(load_Persons, p.PersonName, out personid);
                    }

                    if (groupExists && isFound)
                    {
                        p.PersonId = (await faceServiceClient.GetPersonInLargePersonGroupAsync(this.GroupId, personid)).PersonId.ToString();
                    }
                    else
                    {
                        p.PersonId = (await faceServiceClient.CreatePersonInLargePersonGroupAsync(this.GroupId, p.PersonName)).PersonId.ToString();
                    }
                    Log("Response: Success. Person \"{0}\" (PersonID:{1}) created. Please wait for training.", p.PersonName, p.PersonId);

                    personData.Add(new PersonData(p.PersonId, p.PersonName));

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

                    int j = 0;
                    while (imageList.TryTake(out img))
                    {
                        if (j == 0 && i < ImageWall.num)
                        {
                            imageWall.faceBitmaps[i] = new BitmapImage(new Uri(img));
                            imageWall.id.Add(p.PersonId);
                        }
                        j++;
                        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.AddPersonFaceInLargePersonGroupAsync(this.GroupId, 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((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;
                            }
                        }

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

                            tasks.Clear();
                        }
                    }

                    Persons.Add(p);
                    i++;
                }

                PersonDataUpdate();
                imageWall.UpdateCanvas();
                if (invalidImageCount > 0)
                {
                    Log("Warning: more or less than one face is detected in {0} images, can not add to face list.", invalidImageCount);
                }
                Log("Response: Success. Total {0} faces are detected.", Persons.Sum(p => p.Faces.Count));

                try {
                    // Start train large person group
                    Log("Request: Training group \"{0}\"", this.GroupId);
                    await faceServiceClient.TrainLargePersonGroupAsync(this.GroupId);

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

                        var status = await faceServiceClient.GetLargePersonGroupTrainingStatusAsync(this.GroupId);

                        Log("Response: {0}. Group \"{1}\" training process is {2}", "Success", this.GroupId, status.Status);
                        if (status.Status != ClientContract.Status.Running)
                        {
                            break;
                        }
                    }
                    //IdentifyButton.IsEnabled = true;
                } catch (FaceAPIException ex) {
                    Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                }
            }
            GC.Collect();
        }
Esempio n. 17
0
        /// <summary> Function which submits a frame to the Emotion API. </summary>
        /// <param name="frame"> The video frame to submit. </param>
        /// <returns> A <see cref="Task{LiveCameraResult}"/> representing the asynchronous API call,
        ///     and containing the emotions returned by the API. </returns>
        private async Task TrainCognitiveServicesAsync()
        {
            _faceClient = new FaceAPI.FaceServiceClient(Properties.Settings.Default.FaceAPIKey, Properties.Settings.Default.FaceAPIHost);

            var pgexists = await _faceClient.GetPersonGroupAsync(personGroupId);

            if (pgexists == null)
            {
                await _faceClient.CreatePersonGroupAsync(personGroupId, "My Friends");
            }

            // Define Jose
            CreatePersonResult Josefriend = await _faceClient.CreatePersonAsync(
                // Id of the PersonGroup that the person belonged to
                personGroupId,
                // Name of the person
                "Jose"
                );

            // Define Jose
            CreatePersonResult Aaronfriend = await _faceClient.CreatePersonAsync(
                // Id of the PersonGroup that the person belonged to
                personGroupId,
                // Name of the person
                "Aaron"
                );

            // Directory contains image files of Anna
            const string JoseImageDir = @"C:\Users\joseo\source\repos\FutureofWork-ServTechAPJ2018\FutureofWork-ServTech2018APJ\LiveCameraSample\Pictures\Jose\";

            foreach (string imagePath in Directory.GetFiles(JoseImageDir, "*.jpg"))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    // Detect faces in the image and add to Anna
                    await _faceClient.AddPersonFaceAsync(
                        personGroupId, Josefriend.PersonId, s);
                }
            }
            // Do the same for Bill and Clare

            const string AaronImageDir = @"C:\Users\joseo\source\repos\FutureofWork-ServTechAPJ2018\FutureofWork-ServTech2018APJ\LiveCameraSample\Pictures\Aaron\";

            foreach (string imagePath in Directory.GetFiles(AaronImageDir, "*.jpg"))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    // Detect faces in the image and add to Anna
                    await _faceClient.AddPersonFaceAsync(
                        personGroupId, Aaronfriend.PersonId, s);
                }
            }
            // Do the same for Bill and Clare


            await _faceClient.TrainPersonGroupAsync(personGroupId);

            TrainingStatus trainingStatus = null;

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

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

                await Task.Delay(1000);
            }

            Console.Write("Training successfully completed");
        }
Esempio n. 18
0
 /// <summary>
 /// Initialize Face service client given subscription key
 /// </summary>
 /// <param name="subscriptionKey">subscription key</param>
 public static void Initialize(string subscriptionKey)
 {
     _instance = new FaceServiceClient(subscriptionKey);
 }
        public async Task <Contract.Face[]> DetectAsync(Stream imageStream, bool returnFaceId = true, bool returnFaceLandmarks = false, IEnumerable <FaceAttributeType> returnFaceAttributes = null)
        {
            Contract.Face[] faceArray;
            if (returnFaceAttributes == null)
            {
                object[]        serviceHost = new object[] { this.ServiceHostCn, "detect", returnFaceId, returnFaceLandmarks };
                string          str         = string.Format("{0}/{1}?returnFaceId={2}&returnFaceLandmarks={3}", serviceHost);
                Contract.Face[] faceArray1  = await this.SendRequestAsync <Stream, Contract.Face[]>(HttpMethod.Post, str, imageStream);

                faceArray = faceArray1;
            }
            else
            {
                object[]        objArray   = new object[] { this.ServiceHostCn, "detect", returnFaceId, returnFaceLandmarks, FaceServiceClient.GetAttributeString(returnFaceAttributes) };
                string          str1       = string.Format("{0}/{1}?returnFaceId={2}&returnFaceLandmarks={3}&returnFaceAttributes={4}", objArray);
                Contract.Face[] faceArray2 = await this.SendRequestAsync <Stream, Contract.Face[]>(HttpMethod.Post, str1, imageStream);

                faceArray = faceArray2;
            }
            return(faceArray);
        }