Beispiel #1
0
        private async void NewPersonGroup_Click(object sender, RoutedEventArgs e)
        {
            CreatePersonResult guest = await faceServiceClient.CreatePersonAsync(personGroupId, "Guest");

            //if (guest != null)
            //{
            //    await faceServiceClient.DeletePersonAsync(personGroupId, guest.PersonId);
            //    //The data of the past user has been deleted
            //}

            Stream s = await photoFile.OpenStreamForReadAsync();

            await faceServiceClient.AddPersonFaceAsync(personGroupId, guest.PersonId, s);

            // Training of the new user will now begin.
            status.Text = "Training of the new user will now begin";
            await faceServiceClient.TrainPersonGroupAsync(personGroupId);

            TrainingStatus sstatus = null;

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

                if (sstatus.Status != Status.Running)
                {
                    status.Text = "Person group training complete";
                    break;
                }
                await Task.Delay(1000);
            }
            status.Text = "Training of the new user has been completed. ";
        }
        /// <summary>
        /// Creates person group in Azure face recognition API
        /// </summary>
        /// <returns>boolean</returns>
        public async Task <bool> CreateGroup()
        {
            var people = await _databaseController.GetImageObjects();

            await _faceServiceClient.CreatePersonGroupAsync(_groupId, "fun");

            foreach (var person in people)
            {
                CreatePersonResult result = await _faceServiceClient.CreatePersonAsync(_groupId, person.Id.ToString());

                await _faceServiceClient.AddPersonFaceAsync(_groupId, result.PersonId, RecUtil.GetStreamFromUri(person.ImageContentUri));
            }

            await _faceServiceClient.TrainPersonGroupAsync(_groupId);

            TrainingStatus trainingStatus = null;

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

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

                await Task.Delay(1000);
            }

            return(true);
        }
Beispiel #3
0
        private static async Task DefinePeople(FaceServiceClient faceServiceClient)
        {
            // Define person
            CreatePersonResult suspect1 = await faceServiceClient.CreatePersonAsync(
                // Id of the PersonGroup that the person belonged to
                Constants.PERSON_GROUP_ID,
                // Name of the person
                "Rafał"
                );

            CreatePersonResult suspect2 = await faceServiceClient.CreatePersonAsync(
                Constants.PERSON_GROUP_ID,
                "Marcin"
                );

            CreatePersonResult suspect3 = await faceServiceClient.CreatePersonAsync(
                Constants.PERSON_GROUP_ID,
                "Kacper"
                );

            CreatePersonResult suspect4 = await faceServiceClient.CreatePersonAsync(
                Constants.PERSON_GROUP_ID,
                "Adam"
                );

            await AddPersonFaceAsync(faceServiceClient, suspect1, Paths.suspect1ImageDir);
            await AddPersonFaceAsync(faceServiceClient, suspect2, Paths.suspect2ImageDir);
            await AddPersonFaceAsync(faceServiceClient, suspect3, Paths.suspect3ImageDir);
            await AddPersonFaceAsync(faceServiceClient, suspect4, Paths.suspect4ImageDir);
        }
Beispiel #4
0
        /// <summary>
        ///  Create Empty Person Group
        /// </summary>
        /// <param name="faceCli"></param>
        static async void CreateEmptyPersonGroup(FaceServiceClient faceCli)
        {
            Console.WriteLine("");
            Console.Write("Enter the name of person you wish to create: ");
            string personGroupId = Console.ReadLine();

            inputMode = false;

            try
            {
                // Create Person Group e.g. My friend
                await faceCli.CreatePersonGroupAsync(personGroupId, "Custom group");

                // Create Person in Person Group e.g. My friend -> SmithM
                // in this example we use same e.g. Smith -> SmithM
                CreatePersonResult friend1 = await faceCli.CreatePersonAsync(personGroupId, personGroupId);

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Person Name within Person Group : " + personGroupId + " successfully created");
                Console.ForegroundColor = ConsoleColor.Gray;
                inputMode = true;
                paintMenu();
            }
            catch (FaceAPIException ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                inputMode = true;
                Console.WriteLine(ex.ErrorMessage);
                Console.ForegroundColor = ConsoleColor.Gray;
                paintMenu();
            }
        }
Beispiel #5
0
        public async Task <bool> CreatePerson(byte[] bitmap, string name)
        {
            try
            {
                // Create PERSON
                var newPerson = await _faceClient.CreatePersonAsync(_miriotPersonGroupId, name, JsonConvert.SerializeObject(new UserData()));

                // Add FACE to PERSON
                using (var stream = new MemoryStream(bitmap))
                    await _faceClient.AddPersonFaceAsync(_miriotPersonGroupId, newPerson.PersonId, stream);

                await _faceClient.TrainPersonGroupAsync(_miriotPersonGroupId);

                TrainingStatus state = null;
                while (state?.Status != Status.Running)
                {
                    state = await _faceClient.GetPersonGroupTrainingStatusAsync(_miriotPersonGroupId);
                }

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public async Task <bool> RegisterUser(User user, IEnumerable <byte[]> imgs)
        {
            try
            {
                var persRes = await _client.CreatePersonAsync("users_id", user._id.ToString());

                foreach (var img in imgs)
                {
                    using (var s = new MemoryStream(img))
                    {
                        try
                        {
                            var faceRes = await _client.AddPersonFaceAsync("users_id", persRes.PersonId, s);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine($"RegisterUser.AddImage: {e.Message}");
                        }
                    }
                }
                await _client.TrainPersonGroupAsync("users_id");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"RegisterUser: {ex.ToString()}");
                return(false);
            }

            return(true);
        }
Beispiel #7
0
        /// <summary>
        /// If we want to register a person, we can use this method as a base
        /// </summary>
        /// <returns></returns>
        public async Task CreatePersonAsync()
        {
            var personGroupId = "default";
            var newPerson     = await faceApiClient.CreatePersonAsync(personGroupId, "Mario López");

            var registeredFace = await faceApiClient.AddPersonFaceAsync(personGroupId, newPerson.PersonId, "http://url.de.cara.a.regitrar");
        }
Beispiel #8
0
        public async Task <IActionResult> linkFace([FromBody] CustReq req)
        {
            Claim oid      = User.Claims.FirstOrDefault(x => x.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier");
            var   personId = await _userFunctions.getPersonIdAsync(oid.Value);

            if (String.IsNullOrEmpty(personId))
            {
                var person = await _faceClient.CreatePersonAsync(_configuration["personGroupId"], oid.Value);

                await _userFunctions.setPersonIdAsync(oid.Value, person.PersonId.ToString());

                personId = person.PersonId.ToString();
            }

            byte[]       bytes = Convert.FromBase64String(req.image);
            MemoryStream ms    = new MemoryStream(bytes);

            try
            {
                var returnedFace = await _faceClient.AddPersonFaceAsync(_configuration["personGroupId"], Guid.Parse(personId), ms);

                await _faceClient.TrainPersonGroupAsync(_configuration["personGroupId"]);

                return(Json(returnedFace));
            }
            catch (FaceAPIException e)
            {
                return(Json(new { error = e.ErrorMessage }));
            }
        }
Beispiel #9
0
        private static async Task TrainAsync()
        {
            List <Stream> streams = new List <Stream>();

            for (int i = 1; i < 7; i++)
            {
                string filesString       = @"ms-appx:///Assets/Training (" + i + ").jpg";
                var    randomAcessStream = await RandomAccessStreamReference.CreateFromUri(new Uri(filesString)).OpenReadAsync();

                var stream = randomAcessStream.AsStream();
                streams.Add(stream);
            }
            var faces = new List <Face>();

            foreach (var item in streams)
            {
                var dfaces = await _Client.DetectAsync(item);

                faces.AddRange(dfaces);
            }

            await _Client.CreatePersonGroupAsync(Constants.OwnerGroupId, Constants.OwnerName);

            await _Client.CreatePersonAsync(Constants.OwnerGroupId, faces.Select(f => f.FaceId).ToArray(), Constants.OwnerName);

            await _Client.TrainPersonGroupAsync(Constants.OwnerGroupId);
        }
Beispiel #10
0
        static async Task <Guid> CreatePerson(string personGroupId, string personName)
        {
            // Create the person
            CreatePersonResult dad = await _faceServiceClient.CreatePersonAsync(personGroupId, personName);

            return(dad.PersonId);
        }
        private async void SaveButtonClick()
        {
            if (PersonName != "")
            {
                string personGroupId = "group1";
                Stream image         = await file.OpenStreamForReadAsync();

                Person[] persons = await faceServiceClient.GetPersonsAsync(personGroupId);

                Person person;
                Guid   personId;
                try{
                    person   = persons.Where(item => item.Name == personName).First();
                    personId = person.PersonId;
                }
                catch
                {
                    CreatePersonResult friend1 = await faceServiceClient.CreatePersonAsync(
                        personGroupId,
                        personName
                        );

                    personId = friend1.PersonId;
                }
                await faceServiceClient.AddPersonFaceAsync(personGroupId, personId, image);

                await faceServiceClient.TrainPersonGroupAsync(personGroupId);

                NameStackVisibility = "Collapsed";
                TestText           += "\nThe Person will automatically be allowed next time";
            }
        }
Beispiel #12
0
        async void DefineStudentInStudentList()
        {
            ////Tạo list sinh viên và thêm phần tử vào list
            List <Student> listStudent = new List <Student>();

            //string rootPath = Directory.GetCurrentDirectory();
            //string parentDirectory = Directory.GetParent(rootPath).Parent.FullName + "\\Image";
            for (int i = 1; i < 4; i++)
            {
                Student student = new Student
                {
                    //string imageFile = Path.Combine()
                    Id   = string.Format("SV{0}", i),
                    Name = string.Format("Sinh viên {0}", i),
                    //Image = new Bitmap()
                };
                listStudent.Add(student);
            }
            //Tạo personGroup
            string personGroupId = "G001";

            //await client.CreatePersonGroupAsync(personGroupId, "BI001");


            foreach (Student item in listStudent)
            {
                CreatePersonResult student = await client.CreatePersonAsync(personGroupId, item.Name);
            }
            //Traing
            TrainingModel(personGroupId);
        }
Beispiel #13
0
        private async void CbPersons_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int iPerson = ((ComboBox)sender).SelectedIndex;

            if (iPerson >= 0)
            {
                CbPersons.IsEnabled = false;

                Person = PersonNames[iPerson];

                if (PersonIds[iPerson] == Guid.Empty)
                {
                    PersonId           = (await faceServiceClient.CreatePersonAsync(PersonGroup, Person)).PersonId;
                    PersonIds[iPerson] = PersonId;
                }
                else
                {
                    PersonId = PersonIds[iPerson];
                }

                SpPicture1.Visibility = Visibility.Visible;
                SpPicture2.Visibility = Visibility.Collapsed;
                BtnTakePic1.IsEnabled = true;
            }
        }
        /// <summary>
        /// Add a person and his training images to a specific group
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="personName"></param>9
        /// <param name="imagesPath"></param>
        private static async void addPersonToGroup(string groupId, string personName, List <string> imagesPath)
        {
            try
            {
                Task <AddPersistedFaceResult>[] tAdds = new Task <AddPersistedFaceResult> [imagesPath.Count];

                //Create a person
                var p = Clnt.CreatePersonAsync(groupId, personName, personName);
                p.Wait();
                var p1 = p.Result;

                //Adding person images
                for (int i = 0; i < imagesPath.Count; i++)
                {
                    System.IO.Stream ms = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(imagesPath[i]));

                    tAdds[i] = Clnt.AddPersonFaceAsync(groupId, p1.PersonId, ms);
                }

                Task.WaitAll(tAdds);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Beispiel #15
0
        static async Task CreatePersonTask(string personName)
        {
            //#2. API to add persons to a group
            var result = await faceServiceClient.CreatePersonAsync(personGroupId, personName);

            PersonIdDic.TryAdd(personName, result.PersonId);
        }
        public Person CreatePerson(Person item)
        {
            try
            {
                var dto = Task.Run(() => Api.CreatePersonAsync(item?.GroupName.ToLowerInvariant(), item?.Name, item.UserData)).GetAwaiter().GetResult();

                if (dto?.PersonId != null)
                {
                    var person = new Person
                    {
                        Name      = item.Name,
                        Id        = dto.PersonId,
                        GroupName = item.GroupName,
                        UserData  = item.UserData
                    };

                    return(person);
                }
            }
            catch (FaceAPIException ex)
            {
                throw new FaceApiException(ex.ErrorMessage);
            }

            return(null);
        }
Beispiel #17
0
        public async Task SubirRostroAGrupo(string IdGrupo, string filename)
        {
            bool ExisteGrupo;

            try
            {
                await faceServiceClient.GetPersonGroupAsync(IdGrupo);

                ExisteGrupo = true;
            }
            catch
            {
                ExisteGrupo = false;
            }

            if (!ExisteGrupo)
            {
                await faceServiceClient.CreatePersonGroupAsync(IdGrupo, IdGrupo);
            }

            var tag     = System.IO.Path.GetFileName(filename.Replace("$", ""));
            var persona = await faceServiceClient.CreatePersonAsync(IdGrupo, tag);

            using (var fiStream = File.OpenRead(filename))
            {
                var persistFace = await faceServiceClient.AddPersonFaceAsync(IdGrupo, persona.PersonId, fiStream, tag);
            }
            await faceServiceClient.TrainPersonGroupAsync(IdGrupo);
        }
        public async Task <string> Post(HttpRequestMessage req)
        {
            Console.WriteLine("Uploading Image...");
            try
            {
                string response = "";

                var createPersonResult = await faceServiceClient.CreatePersonAsync(Request.Query["personGroupId"], Request.Query["personName"]);

                response = $"Person Created: {createPersonResult.PersonId.ToString()}\n";


                Console.WriteLine($"Person Created: {createPersonResult.PersonId.ToString()}\n");



                using (Stream s = Request.Body)
                {
                    var addPersonFaceResult = await faceServiceClient.AddPersonFaceAsync(Request.Query["personGroupId"], createPersonResult.PersonId, s);

                    response = response + $"Face Added: {addPersonFaceResult.PersistedFaceId.ToString()}\n";

                    Console.WriteLine($"Face Added: {addPersonFaceResult.PersistedFaceId.ToString()}\n");

                    CloudTable PersonInfo = await CreateTableAsync("PersonInfo");

                    TableBatchOperation batchOperation = new TableBatchOperation();
                    var personEntity = new PersonInfo()
                    {
                        PersonName = Request.Query["personName"], PersonCompany = Request.Query["personCompany"]
                    };

                    var tableEntity = personEntity as TableEntity;
                    tableEntity.PartitionKey = createPersonResult.PersonId.ToString();
                    tableEntity.RowKey       = addPersonFaceResult.PersistedFaceId.ToString();


                    batchOperation.Insert(personEntity);
                    IList <TableResult> results = await PersonInfo.ExecuteBatchAsync(batchOperation);

                    if (results.Count > 0)
                    {
                        response = response + $"Table Updated\n";
                        Console.WriteLine($"Table Updated\n");
                    }

                    await faceServiceClient.TrainPersonGroupAsync(personGroupId);

                    Console.WriteLine($"Training Started\n");
                }


                return(response);
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
        }
Beispiel #19
0
        /// <summary>
        /// 加入人員的動作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnAddPerson_Click(object sender, EventArgs e)
        {
            string strPersonGroupId = ((Models.CognitiveModels.ListItem)lbxPersonGroup.SelectedItem).Value;
            await face.CreatePersonAsync(strPersonGroupId, txtPerson.Text);

            this.BindPersons();
            txtPerson.Text = "";
        }
Beispiel #20
0
        // Returns person ID.
        public async Task <Guid> CreatePersonAsync(string pegawaiId, string name)
        {
            await CreatePersonGroupIfNotExist();

            var result = await faceServiceClient.CreatePersonAsync(PERSON_GROUP_ID, $"{name}");

            return(result.PersonId);
        }
        public async Task <string> Post(string lastName, string firstName, string permission) //Create a member
        {
            FaceServiceClient  faceClient    = new FaceServiceClient(Configuration.Get("AppSettings:OxfordSubscriptionKeyPrimary"));
            string             memberGroupId = Configuration.Get("AppSettings:OxfordSubscriptionKeyPrimary");
            CreatePersonResult memberDetail  = await faceClient.CreatePersonAsync(memberGroupId, lastName + " " + firstName, permission);

            return(memberDetail.PersonId.ToString());
        }
Beispiel #22
0
        public async Task <string> CreatePersonGroupPersonAsync(string personGroupId, string name, ConnectionApiData connectionApiData)
        {
            using (var faceClient = new FaceServiceClient(connectionApiData.SubscriptionKey, connectionApiData.Location))
            {
                var result = await faceClient.CreatePersonAsync(personGroupId, name);

                return(result.PersonId.ToString());
            }
        }
Beispiel #23
0
        public async Task <bool> Face()
        {
            var test = true;
            FaceServiceClient faceServiceClient = new FaceServiceClient("57dfa44fcc82469fb81ec031ba2f43c6", "https://westcentralus.api.cognitive.microsoft.com/face/v1.0");
            // Create an empty PersonGroup
            string personGroupId = "myfriends";
            //await faceServiceClient.CreatePersonGroupAsync(personGroupId, "MyFriends");

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

            const string friend1ImageDir = @"C:/Users/Megaport/Pictures/face";

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

            TrainingStatus trainingStatus = null;

            trainingStatus = await faceServiceClient.GetPersonGroupTrainingStatusAsync(personGroupId);

            string testImageFile = "ftp://35.190.168.129/images/test1.png";

            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)
                {
                    if (identifyResult.Candidates.Length == 0)
                    {
                        test = false;
                    }
                    else
                    {
                        test = true;
                    }
                }
            }
            return(test);
        }
        async void ExecuteTrainFaceAPI()
        {
            var people = new List <Person>
            {
                new Person {
                    FullName = "Shaun",
                    PhotoUrl = "https://scontent-mxp1-1.xx.fbcdn.net/v/t1.0-9/12038495_916990261703186_7575801463680622880_n.jpg?oh=db07dbdb3f728b56460545d3991d1063&oe=58C4A1BF"
                },
                new Person {
                    FullName = "Katya",
                    PhotoUrl = "https://scontent-mxp1-1.xx.fbcdn.net/v/t1.0-9/13659191_1380711775279518_6270811927728068493_n.jpg?oh=b143f5356842bb338ab05d24b786b748&oe=58C612CD"
                },
                new Person {
                    FullName = "Kevin",
                    PhotoUrl = "https://www.pizza4u.com.mt/media/1005/kevin-farrugia.jpg"
                },
                new Person {
                    FullName = "Gosia",
                    PhotoUrl = "https://scontent-mxp1-1.xx.fbcdn.net/v/t1.0-9/10347484_10201839306779156_4563104125806602622_n.jpg?oh=15fdba843aed15636ae0f5ac209ce6e1&oe=58B664D1"
                },
                new Person {
                    FullName = "Alberto",
                    PhotoUrl = "https://trello-attachments.s3.amazonaws.com/568fc6d9a159da4a0a38a6e5/278x359/6f5b8c4486f5d059b9b6f91a0d2c04c4/4a6f310c-a2a1-49e0-8df5-3c859485207c.jpg"
                }
            };

            try
            {
                IsBusy = true;

                // Step 1 - Create Person Group
                personGroupId = Guid.NewGuid().ToString();
                await faceServiceClient.CreatePersonGroupAsync(personGroupId, "Incredible Web Employees");

                // Step 2 - Add persons (and faces) to person group.
                foreach (var person in people)
                {
                    // Step 2a - Create a new person, identified by their name.
                    var p = await faceServiceClient.CreatePersonAsync(personGroupId, person.FullName);

                    // Step 3a - Add a face for that person.
                    await faceServiceClient.AddPersonFaceAsync(personGroupId, p.PersonId, person.PhotoUrl);
                }

                // Step 3 - Train facial recognition model.
                await faceServiceClient.TrainPersonGroupAsync(personGroupId);

                IsBusy = false;
            }
            catch (Exception ex)
            {
                IsBusy = false;
                UserDialogs.Instance.ShowError("Training has not finished");
            }
        }
Beispiel #25
0
        public void InitializePersonGroup(string personGroupId)
        {
            var personIdKen = Task.Run(() => _fsClient.CreatePersonAsync(personGroupId, "lynn", "Lynn Li")).Result.PersonId;

            using (FileStream fsKen = new FileStream(@"C:\Users\lli508\Desktop\photo\me\1.jpg", FileMode.Open))
            {
                var personFaceId = Task.Run(() => _fsClient.AddPersonFaceAsync(personGroupId, personIdKen, fsKen)).Result.PersistedFaceId;
            }

            Task.Run(() => _fsClient.TrainPersonGroupAsync(personGroupId)).GetAwaiter().GetResult();
        }
        public async Task LoadDataAsync()
        {
            Message = "Loading Data..";

            // Check if face group alredy exists, otherwise create it.
            try
            {
                await faceClient.GetPersonGroupAsync(Settings.PersonGroupId);
            }
            catch (FaceAPIException ex)
            {
                if (ex.ErrorCode == "PersonGroupNotFound")
                {
                    await faceClient.CreatePersonGroupAsync(Settings.PersonGroupId, Settings.PersonGroupId);
                }
                else
                {
                    throw;
                }
            }

            currentEvent = await meetupService.GetCurrentEventAsync();

            if (currentEvent == null)
            {
                Message = "No event scheduled.";
                return;
            }

            registeredPersons = (await faceClient.GetPersonsAsync(Settings.PersonGroupId)).ToList();
            RSVPs             = await meetupService.GetRSVPsAsync(currentEvent.Id);

            // Get comments start with 'Welcome' to track who comes to the event.
            RSVPComments = (await meetupService.GetCommentsAsync(currentEvent.Id)).Where(x => x.CommentDetail.StartsWith("Welcome ")).ToList();

            // Check if RSVPed meetup member is registered to Face API.
            foreach (RSVP rsvp in RSVPs)
            {
                var registeredPerson = registeredPersons.FirstOrDefault(x => x.Name == rsvp.Member.Name);
                if (registeredPerson == null)
                {
                    var userData = new JObject();
                    userData["memberId"] = rsvp.Member.Id;
                    var createdPersonResult = await faceClient.CreatePersonAsync(Settings.PersonGroupId, rsvp.Member.Name, userData.ToString());

                    registeredPersons.Add(await faceClient.GetPersonAsync(Settings.PersonGroupId, createdPersonResult.PersonId));
                }
            }

            await mediaCapture.StartPreviewAsync();

            Identify();
        }
        public async Task UpsertPersonAsync(StorageFile image, string personName)
        {
            Log?.WriteLine($"Upsert person: {personName}");

            // person group
            try
            {
                var personGroup = await _faceClient.GetPersonGroupAsync(_groupName);

                Log?.WriteLine($"Found person group: {personGroup.Name}");
            }
            catch (FaceAPIException ex)
            {
                if (ex.ErrorCode == "PersonGroupNotFound")
                {
                    Log?.WriteLine("Creating person group");
                    await _faceClient.CreatePersonGroupAsync(_groupName, _groupName);
                }
            }

            // person
            var people = await _faceClient.GetPersonsAsync(_groupName);

            var personId = people.FirstOrDefault(p => p.Name.ToLowerInvariant() == personName.ToLowerInvariant())?.PersonId;

            if (personId == null || personId == Guid.Empty)
            {
                personId = (await _faceClient.CreatePersonAsync(_groupName, personName)).PersonId;
            }

            // face
            await Task.Run(async() =>
            {
                using (var fileStream = File.OpenRead(image.Path))
                {
                    await _faceClient.AddPersonFaceAsync(_groupName, (Guid)personId, fileStream, image.Path);
                    await _faceClient.TrainPersonGroupAsync(_groupName);

                    while (true)
                    {
                        var trainingStatus = await _faceClient.GetPersonGroupTrainingStatusAsync(_groupName);
                        Log?.WriteLine($"Training Status: {trainingStatus.Status.ToString()}");
                        if (trainingStatus.Status != Microsoft.ProjectOxford.Face.Contract.Status.Running)
                        {
                            break;
                        }

                        await Task.Delay(1500);
                    }
                }
            });
        }
Beispiel #28
0
        public async Task <bool> AddImageForPerson(PhotoFace photoFace, IRandomAccessStream stream)
        {
            if (photoFace == null || photoFace.Name == null)
            {
                return(false);
            }

            bool trained = false;

            // create group
            try
            {
                if (!await CheckIfGroupExistsAsync())
                {
                    await _client.CreatePersonGroupAsync(_groupId, _groupId);
                }

                if (photoFace.PersonId == null || _personList == null || !_personList.Any(p => p.PersonId == photoFace.PersonId))
                {
                    photoFace.PersonId = (await _client.CreatePersonAsync(_groupId, photoFace.Name)).PersonId;
                }

                await _client.AddPersonFaceAsync(_groupId, photoFace.PersonId, stream.AsStream(), targetFace : photoFace.Rect);

                await _client.TrainPersonGroupAsync(_groupId);

                while (!trained)
                {
                    await Task.Delay(1000);

                    var status = await _client.GetPersonGroupTrainingStatusAsync(_groupId);

                    switch (status.Status)
                    {
                    case Status.Succeeded:
                        trained = true;
                        break;

                    case Status.Failed:
                        return(false);
                    }
                }

                _personList = await _client.GetPersonsAsync(_groupId);

                return(true);
            }
            catch (FaceAPIException ex)
            {
                return(false);
            }
        }
Beispiel #29
0
        private async static void TrainNew()
        {
            Console.WriteLine("Enter the Person Group Id:");
            string personGroupId = Console.ReadLine();

            string path = @"..\..\..\Images\Train";

            foreach (var folderPath in Directory.GetDirectories(Path.GetFullPath(path)))
            {
                string folderName = folderPath.Remove(0, folderPath.LastIndexOf('\\') + 1);
                var    tempArray  = folderName.Split(',');
                folderName = $"{EveryFirstCharToUpper(tempArray[1].ToLower())} {EveryFirstCharToUpper(tempArray[0].ToLower())}";

                Console.WriteLine($"Creating new Person for {folderName}");

                var personResult = await _faceServiceClient.CreatePersonAsync(personGroupId, folderName);

                if (personResult != null)
                {
                    foreach (var filePath in Directory.EnumerateFiles(folderPath, "*.*"))
                    {
                        try
                        {
                            Console.WriteLine(filePath);
                            using (var fileStream = File.OpenRead(filePath))
                            {
                                var personFaceResult = await _faceServiceClient.AddPersonFaceAsync(personGroupId, personResult.PersonId, fileStream);

                                Console.WriteLine($"\t Persisted Face Id for {folderName}: {personFaceResult.PersistedFaceId}");
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"Exception thrown at image {filePath} - {ex.Message}");
                        }
                    }
                }

                if (Directory.EnumerateFiles(folderPath, "*.*").Any())
                {
                    Console.WriteLine("===================================");
                    Console.WriteLine($"Finished Adding Faces for {folderName}");
                    Console.WriteLine("===================================");
                }
                else
                {
                    Console.WriteLine($"No available images for {folderName}");
                }
            }

            await TrainFaces(personGroupId);
        }
        private async void addIndividual(String name)
        {
            CreatePersonResult friend1 = await faceServiceClient.CreatePersonAsync("myfriends", name);

            const string friend1ImageDir = @"<Directory with images of person>";

            foreach (string imagePath in Directory.GetFiles(friend1ImageDir, "*.jpg"))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    try
                    {
                        await faceServiceClient.AddPersonFaceAsync(
                            "myfriends", friend1.PersonId, s);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
        }
        /// <summary>
        /// Add photos to the training group using Microsoft Face API
        /// </summary>
        /// <param name="Photos">List of photos to add</param>
        /// <param name="PersonGroupID">Name of the training group</param>
        /// <returns></returns>
        public async Task addPhotosToTrainingGroup(Dictionary<string, PhotoPerson> Photos, string PersonGroupID)
        {
            IFaceServiceClient faceClient = new FaceServiceClient(SubscriptionKey);

            // Get the group and add photos to the group.
            // The input dictionary is organized by person ID.  The output dictionary is organized by the GUID returned by the added photo from the API.
            try
            {
                await faceClient.GetPersonGroupAsync(PersonGroupID);

                // training photos can support multiple pictures per person (more pictures will make the training more effective).  
                // each photo is added as a Face object within the Face API and attached to a person.

                foreach (PhotoPerson person in Photos.Values)
                {
                    Person p = new Person();
                    p.Name = person.Name;
                    p.PersonId = Guid.NewGuid();

                    List<Guid> faceIDs = new List<Guid>();

                    
                    foreach (Photo photo in person.Photos)
                    {
                        Stream stream = new MemoryStream(photo.Image);
                        Face[] face = await faceClient.DetectAsync(stream);

                        // check for multiple faces - should only have one for a training set.
                        if (face.Length != 1)
                            throw new FaceDetectionException("Expected to detect 1 face but found " + face.Length + " faces for person " + p.Name);
                        else
                            faceIDs.Add(face[0].FaceId);
                    }

                    Guid[] faceIDarray = faceIDs.ToArray();

                    // create the person in the training group with the image array of faces.
                    CreatePersonResult result = await faceClient.CreatePersonAsync(PersonGroupID, faceIDarray, p.Name, null);
                    p.PersonId = result.PersonId;
                    TrainingPhotos.Add(p.PersonId, person);

                }

                await faceClient.TrainPersonGroupAsync(PersonGroupID);
                // Wait until train completed
                while (true)
                {
                    await Task.Delay(1000);
                    var status = await faceClient.GetPersonGroupTrainingStatusAsync(PersonGroupID);
                    if (status.Status != "running")
                    {
                        break;
                    }
                }
            }
            catch (ClientException ex)
            {
                throw;
            }



        }
        /// <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);
                }
            }
        }