Пример #1
0
 public Task <AddPersistedFaceResult> AddPersonFaceAsync(string personGroupId,
                                                         Guid personId,
                                                         string imageUrl,
                                                         string userData          = null,
                                                         FaceRectangle targetFace = null)
 {
     return(innerClient.AddPersonFaceAsync(personGroupId, personId, imageUrl, userData, targetFace));
 }
        private async Task RegisterNameAsync(string person, string path, string personGroupId)
        {
            foreach (string imagePath in Directory.GetFiles(path, "*.jpg"))
            {
                // Define person
                CreatePersonResult friend1 = await faceServiceClient.CreatePersonAsync(
                    // Id of the PersonGroup that the person belonged to
                    personGroupId,
                    // Name of the person
                    person
                    );

                using (Stream s = File.OpenRead(imagePath))
                {
                    // Detect faces in the image and add to Anna
                    await faceServiceClient.AddPersonFaceAsync(
                        personGroupId, friend1.PersonId, s);
                }
            }
            var em = db.Tables["Employee"].Select("Emp_name like '" + person + "'");

            if (em.Count() <= 0)
            {
                db.Employee.AddEmployeeRow(person);
                db.WriteXml(databaseName);
            }
        }
Пример #3
0
        private async Task CreatePersons(string selectPath)
        {
            Console.WriteLine(selectPath);
            foreach (var dir in Directory.EnumerateDirectories(selectPath))
            {
                Console.WriteLine(dir);
                Console.WriteLine(Path.GetFileName(dir));
                // Define Anna
                CreatePersonResult friend = await _faceServiceClient.CreatePersonAsync(
                    // Id of the person group that the person belonged to
                    personGroupId,
                    // Name of the person
                    Path.GetFileName(dir)
                    );

                Console.WriteLine("CreatePersonAsync--------------------------" + Path.GetFileName(dir));

                foreach (var file in Directory.EnumerateFiles(dir, "*.jpg", SearchOption.AllDirectories))
                {
                    Console.WriteLine(file);
                    Console.WriteLine(Path.GetFileName(file));
                    // Directory contains image files of folder
                    using (Stream s = File.OpenRead(file))
                    {
                        // Detect faces in the image and add to Anna
                        await _faceServiceClient.AddPersonFaceAsync(personGroupId, friend.PersonId, s);

                        Console.WriteLine("AddPersonFaceAsync------------------------------" + file);
                    }
                }
            }
        }
Пример #4
0
        private async void addFaceAndTrainData(string imagePath, System.Guid personId)
        {
            try
            {
                using (Stream imageFileStream = File.OpenRead(imagePath))
                {
                    AddPersistedFaceResult faceRes = await faceServiceClient.AddPersonFaceAsync(this.personGroupId, personId, imageFileStream);

                    Console.Out.WriteLine("Added face to Person with Id " + faceRes.PersistedFaceId);
                }


                await faceServiceClient.TrainPersonGroupAsync(this.personGroupId);

                TrainingStatus status = null;
                do
                {
                    status = await faceServiceClient.GetPersonGroupTrainingStatusAsync(this.personGroupId);
                } while (status.Status.ToString() != "Succeeded");
            }
            catch (FaceAPIException f)
            {
                MessageBox.Show(f.ErrorCode, f.ErrorMessage);
            }
        }
Пример #5
0
        private async void Train()
        {
            String personGroupId = "students";
            await faceServiceClient.UpdatePersonGroupAsync(personGroupId, "SISstudenti");


            string friend1ImageDir = AppDomain.CurrentDomain.BaseDirectory + @"Slike\" + rfid + @"\";

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

            TrainingStatus trainingStatus = null;

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

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

                await Task.Delay(1000);
            }
        }
        /// <summary>
        /// Create a new PersonGroup, then proceed to send pictures of each listed user, uploading them from given directory
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnCreateGroup_Click(object sender, EventArgs e)
        {
            try
            {
                _groupId = txtGroupName.Text.ToLower().Replace(" ", "");

                try
                {
                    await faceServiceClient.DeletePersonGroupAsync(_groupId);
                } catch { }

                await faceServiceClient.CreatePersonGroupAsync(_groupId, txtGroupName.Text);

                foreach (var u in listUsers.Items)
                {
                    CreatePersonResult person = await faceServiceClient.CreatePersonAsync(_groupId, u.ToString());

                    foreach (string imagePath in Directory.GetFiles(txtImageFolder.Text + "\\" + u.ToString()))
                    {
                        using (Stream s = File.OpenRead(imagePath))
                        {
                            await faceServiceClient.AddPersonFaceAsync(_groupId, person.PersonId, s);
                        }
                    }

                    await Task.Delay(1000);
                }

                MessageBox.Show("Group successfully created");
            } catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Пример #7
0
        /// <summary>
        /// Add a new person(profile) to the person group
        /// </summary>
        /// <param name="email">Email of the person to be added</param>
        public async void addPerson(string email, StorageFile sf)
        {
            try
            {
                // Define Person
                CreatePersonResult person = await faceServiceClient.CreatePersonAsync(szPersonGroupID, email);

                string imagePath = sf.Path;
                Debug.WriteLine(imagePath);

                await Task.Run(() =>
                {
                    Task.Yield();
                    stream = File.OpenRead(sf.Path);

                    Debug.WriteLine("File read.");
                });

                await faceServiceClient.AddPersonFaceAsync(szPersonGroupID, person.PersonId, stream);

                Debug.WriteLine("Face added.");
            }
            catch (Exception e)
            {
                Debug.WriteLine("ERROR:");
                Debug.WriteLine(e.StackTrace);
            }
            train();
        }
Пример #8
0
        private async Task FaceAddInPerson(string image)
        {
            // Call the Face API.
            try
            {
                using (Stream imageFileStream = File.OpenRead(image))
                {
                    var result = await _faceServiceClient.AddPersonFaceAsync("grupo", personId, imageFileStream);

                    faceId1 = result.PersistedFaceId;
                }

                await _faceServiceClient.TrainPersonGroupAsync("grupo");
            }
            // Catch and display Face API errors.
            catch (FaceAPIException f)
            {
                await DisplayAlert("Error", f.ErrorMessage, "ok");
            }
            // Catch and display all other errors.
            catch (Exception e)
            {
                await DisplayAlert("Error", e.Message, "ok");
            }
        }
        private async void SetupPersonGroup()
        {
            const string lilianImageDir = @"Assets\PersonGroup\Lilian\";

            try
            {
                //if (faceServiceClient.) <-- need to check if it exists first
                await faceServiceClient.CreatePersonGroupAsync(personGroup, personGroup);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return;
            }

            // Define Users
            CreatePersonResult lilian = await faceServiceClient.CreatePersonAsync(
                personGroup,
                "Lilian"
                );

            foreach (string imagePath in Directory.GetFiles(lilianImageDir, "*.jpg"))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    // Detect faces in the image and add to Lilian
                    await faceServiceClient.AddPersonFaceAsync(
                        personGroup, lilian.PersonId, s);
                }
            }

            //Train model
            try
            {
                await faceServiceClient.TrainPersonGroupAsync(personGroup);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            TrainingStatus trainingStatus = null;

            while (true)
            {
                trainingStatus = await faceServiceClient.GetPersonGroupTrainingStatusAsync(personGroup);

                if (trainingStatus.Status.ToString() != "running")
                {
                    break;
                }

                await Task.Delay(1000);
            }
        }
Пример #10
0
        /// <summary>
        /// Add face to both Cloud Face API and local whitelist
        /// </summary>
        /// <param name="personId"></param>
        /// <param name="faceId"></param>
        /// <param name="imagePath"></param>
        /// <returns></returns>
        private async Task AddFace(Guid personId, Guid faceId, string imagePath)
        {
            // prevent running synchronous call on UI thread
            await Task.Run(async() => {
                using (Stream imageStream = File.OpenRead(imagePath)) {
                    var result = await _faceApiClient.AddPersonFaceAsync(WhitelistId, personId, imageStream);
                }

                _whitelist.AddFace(personId, faceId, imagePath);
            });
        }
Пример #11
0
        /// <summary>
        /// Add face to both Cloud Face API and local whitelist
        /// </summary>
        /// <param name="personId"></param>
        /// <param name="faceId"></param>
        /// <param name="imagePath"></param>
        /// <returns></returns>
        private async Task AddFace(Guid personId, Guid faceId, string imagePath)
        {
            await Task.Run(async() =>
            {
                using (Stream imageStream = File.OpenRead(imagePath))
                {
                    await _faceApiClient.AddPersonFaceAsync(WhitelistId, personId, imageStream);
                }
            });

            _whitelist.AddFace(personId, faceId, imagePath);
        }
Пример #12
0
        // Add a new user to the users list
        public async void addNewUser(String newUserName, String imagesFolderPath, String groupId)
        {
            CreatePersonResult person = await faceServiceClient.CreatePersonAsync(groupId, newUserName);

            foreach (string imagePath in Directory.GetFiles(imagesFolderPath))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    await faceServiceClient.AddPersonFaceAsync(groupId, person.PersonId, s);
                }
            }
        }
Пример #13
0
        public async Task TrainFacialRecognizitionAsync(string personGroupId, string personGroupName, string filePath)
        {
            CreatePersonResult person = await faceServiceClient.CreatePersonAsync(personGroupId, personGroupName);

            foreach (string imagePath in Directory.GetFiles(filePath))
            {
                using (Stream s = System.IO.File.OpenRead(imagePath))
                {
                    await faceServiceClient.AddPersonFaceAsync(personGroupId, person.PersonId, s);
                }
            }
        }
Пример #14
0
        private async Task AddFaceToPerson(string personGroupId, Microsoft.ProjectOxford.Face.Contract.CreatePersonResult person, string friendImageDir)
        {
            foreach (string imagePath in Directory.GetFiles(friendImageDir, "*.jpg"))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    // Detect faces in the image and add to Anna
                    await faceClient.AddPersonFaceAsync(personGroupId, person.PersonId, s);

                    //await faceClient.PersonGroupPerson.AddFaceFromStreamAsync(
                    //    personGroupId, ana.PersonId, s);
                }
            }
        }
Пример #15
0
        public async void TestMethodAsync()
        {
            try
            {
                await faceServiceClient.CreatePersonGroupAsync(personGroupId, personGroupId);

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

                // Directory contains image files of the person
                string friend1ImageDir = @"D:\Pictures\Anna";


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

                // Do the same for Bill and Clare
                await faceServiceClient.TrainPersonGroupAsync(personGroupId);

                TrainingStatus trainingStatus = null;
                while (true)
                {
                    trainingStatus = await faceServiceClient.GetPersonGroupTrainingStatusAsync(personGroupId);

                    if (!(trainingStatus.Status.Equals("running")))
                    {
                        break;
                    }

                    await Task.Delay(1000);
                }
            }
            catch (Exception e)
            {
            }
        }
Пример #16
0
        private async void BtnLoadToTrainer_Click(object sender, RoutedEventArgs e)
        {
            if (groupName == "" || personName == "")
            {
                MessageBox.Show("Blank group or person name");
                return;
            }


            _(String.Format("Creating group {0}...", groupId));
            try
            {
                await faceServiceClient.CreatePersonGroupAsync(groupId, groupName);
            }
            catch (FaceAPIException eCreatePersonGroupAsync)
            {
                _(String.Format("{0}", eCreatePersonGroupAsync.ErrorMessage));
            }

            _("Creating person " + personName + "...");
            try
            {
                CreatePersonResult person = await faceServiceClient.CreatePersonAsync(groupId, personName);

                foreach (String imagePath in imagePaths)
                {
                    using (Stream s = File.OpenRead(imagePath))
                    {
                        try
                        {
                            _(String.Format("Processing {0}...", imagePath));
                            await faceServiceClient.AddPersonFaceAsync(groupId, person.PersonId, s);
                        }
                        catch (FaceAPIException eAddPersonFaceAsync)
                        {
                            _(eAddPersonFaceAsync.ErrorMessage);
                        }
                    }
                }
                _("Done.");
            }
            catch (FaceAPIException eCreatePerson)
            {
                _(eCreatePerson.ErrorMessage);
            }
        }
Пример #17
0
        private async Task <List <Stream> > AddFaceToPerson(string personGroupId, CreatePersonResult person, IEnumerable <Stream> personPictures)
        {
            List <Stream> facesNotDetected = new List <Stream>();

            foreach (var streamFace in personPictures)
            {
                try
                {
                    await faceClient.AddPersonFaceAsync(personGroupId, person.PersonId, streamFace);
                }
                catch (FaceAPIException ex)
                {
                    facesNotDetected.Add(streamFace);
                }
            }
            return(facesNotDetected);
        }
Пример #18
0
        private async Task <Unit> RegisterPerson()
        {
            var person = await client.CreatePersonAsync(group, Name);

            foreach (var imageData in Images)
            {
                using (var imageStream = await imageData.Source.OpenStreamForReadAsync())
                {
                    await client.AddPersonFaceAsync(group, person.PersonId, imageStream);
                }
            }

            await client.TrainPersonGroupAsync(group);

            Name = string.Empty;
            return(Unit.Default);
        }
Пример #19
0
        public async void AddPresons(string friend1ImageDi)
        {
            try
            {
                await faceServiceClient.CreatePersonGroupAsync(personGroupId, "Athmane");

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

                const string friend1ImageDir = @"C:\Users\Athmane\Pictures\moi";//@"C:\Users\Athmane\Pictures\test";//"C:\Users\Athmane\Downloads\Cognitive-Face-Windows-master\Cognitive-Face-Windows-master\Data\PersonGroup\Family1-Mom";

                foreach (string imagePath in Directory.GetFiles(friend1ImageDir, "*.JPEG"))
                {
                    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;
                while (true)
                {
                    trainingStatus = await faceServiceClient.GetPersonGroupTrainingStatusAsync(personGroupId);

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

                    await Task.Delay(1000);
                }
            }
            catch (Exception ec)
            {
                return;
            }
        }
Пример #20
0
 private void UploadFace(HttpPostedFileBase file, Guid personId)
 {
     try
     {
         Log("Add Face");
         faceServiceClient.AddPersonFaceAsync(personGroupId, personId, file.InputStream);
         Log("Added Face");
     }
     // Catch and display Face API errors.
     catch (FaceAPIException f)
     {
         Log(f.ErrorMessage);
     }
     // Catch and display all other errors.
     catch (Exception e)
     {
         Log(e.Message);
     }
 }
Пример #21
0
        public async Task <IActionResult> Register(string login, [FromBody] byte[] photo, string userName = "")
        {
            var user = new
            {
                login    = login,
                userName = userName,
                photo    = photo
            };

            // проверить по логину запись в базе данных
            // если такая запись есть, обломать
            // ...
            // ...
            // ...

            //если такой записи нет, регистрируем - получаем новый PersonnId
            try
            {
                using (Stream imageFileStream = new MemoryStream(photo))
                {
                    //await faceServiceClient.CreatePersonGroupAsync(groupName, groupName); // считаем, что у нас уже зарегистрироавна группа
                    CreatePersonResult person = await faceServiceClient.CreatePersonAsync(groupName, userName);

                    AddPersistedFaceResult faceResult = await faceServiceClient.AddPersonFaceAsync(groupName, person.PersonId, imageFileStream);

                    var result = new
                    {
                        RegisterResult = true,
                        PersonId       = person.PersonId
                    };
                    return(Json(result));
                }
            } catch (Exception ex)
            {
                var result = new
                {
                    RegisterResult = false,
                    Message        = "Ошибка при регистрации, возможно такой пользователь уже зарегистрирован",
                    ErrorMessage   = ex.Data["ErrorMessage"],
                };
                return(Json(result));
            }
        }
        /// <summary>
        /// Tab 3 Register a person with a bunch of registered face images in section 'Register Person'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private async void ResigterPersonButton_Click(object sender, RoutedEventArgs e)
        {
            int  itemNum       = Tab3PersonGroupIDComboBox.Items.Count;
            int  selectedGroup = Tab3PersonGroupIDComboBox.SelectedIndex;
            bool flag1         = string.IsNullOrWhiteSpace(Tab3PersonNameTextBox.Text);
            bool flag2         = string.IsNullOrWhiteSpace(Tab3DirectoryOfRegisterPersonTextBox.Text);

            if (itemNum == 0)
            {
                MessageBox.Show("Please define the person group ID first in page 2");
            }
            if (flag1)
            {
                MessageBox.Show("Please input the person name");
                Tab3PersonNameTextBox.Focus();
            }

            if (flag2)
            {
                MessageBox.Show("Please select a directory of register voter's images");
            }
            if (selectedGroup == -1)
            {
                MessageBox.Show("Please select a group");
            }
            if (itemNum != 0 && !flag1 && !flag2 && selectedGroup != -1)
            {
                string             personGroupId = Tab3PersonGroupIDComboBox.Text;
                string             personName    = Tab3PersonNameTextBox.Text;
                CreatePersonResult myPerson      = await faceServiceClient.CreatePersonAsync(personGroupId, personName);

                foreach (string imagePath in Directory.GetFiles(Tab3DirectoryOfRegisterPersonTextBox.Text))
                {
                    using (Stream s = File.OpenRead(imagePath))
                    {
                        await faceServiceClient.AddPersonFaceAsync(personGroupId, myPerson.PersonId, s);
                    }
                }

                MessageBox.Show("Succeed register person");
            }
        }
        /// <summary>
        ///     사람에 얼굴 등록하기
        /// </summary>
        /// <param name="personId"></param>
        /// <param name="fileStream"></param>
        /// <returns></returns>
        public async Task <AddPersistedFaceResult> AddPersonFaceAsync(Guid personId, Stream fileStream)
        {
            try
            {
                // Detect faces in the image and add to Anna
                var result = await faceServiceClient.AddPersonFaceAsync(
                    _personGroupId, personId, fileStream);

                return(result);
            }
            catch (FaceAPIException fae)
            {
                Debug.WriteLine(fae.ErrorMessage);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return(null);
        }
        private async Task <String> addperson(Stream path, String personId)
        {
            try
            {
                CreatePersonResult persons = await faceServiceClient.CreatePersonAsync(groupId, personId);

                var personIds = persons.PersonId;
                using (path)
                {
                    var persistedperson = await faceServiceClient.AddPersonFaceAsync(groupId, personIds, path);

                    await faceServiceClient.TrainPersonGroupAsync(groupId);

                    return("Success");
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
Пример #25
0
        private async void btnCreatePerson_Click(object sender, RoutedEventArgs e)
        {
            CreatePersonResult person = await faceServiceClient.CreatePersonAsync(
                // Id of the person group that the person belonged to
                txtExisitingPersonGroupID.Text,
                // Name of the person
                txtPersonName.Text
                );

            foreach (string imagePath in Directory.GetFiles(txtFolderURL.Text, "*.jpg"))
            {
                using (Stream s = File.OpenRead(imagePath))
                {
                    // Detect faces in the image and add to the Person
                    await faceServiceClient.AddPersonFaceAsync(txtExisitingPersonGroupID.Text, person.PersonId, s);
                }
            }

            //Call the training method
            await faceServiceClient.TrainPersonGroupAsync(txtExisitingPersonGroupID.Text);


            TrainingStatus trainingStatus = null;

            while (true)
            {
                trainingStatus = await faceServiceClient.GetPersonGroupTrainingStatusAsync(txtExisitingPersonGroupID.Text);

                if (trainingStatus.Status.ToString() != "running")
                {
                    break;
                }

                await Task.Delay(1000);
            }

            addToDatabase(txtPersonName.Text, txtPassword.Text, txtExisitingPersonGroupID.Text, person.PersonId.ToString());

            txtMessage2.Text = "Person: " + txtPersonName.Text + " was Successfully Created!";
        }
        public async Task <IActionResult> Register(string key, int faceIndex, string name)
        {
            // get the file from Storage
            var storageObject = _storageService.Get(key) as object[];
            var responseModel = storageObject[0] as ResponseModel;
            var file          = storageObject[1] as IFormFile;

            // create new person
            CreatePersonResult person = await _faceService.CreatePersonAsync(_personGroupId, name);

            string filePath = Path.Combine(Directory.GetCurrentDirectory(), "images", key);

            using (Stream fileStream = new FileStream(filePath, FileMode.Open))
            {
                // register face - person
                await _faceService.AddPersonFaceAsync(_personGroupId, person.PersonId, fileStream, null, responseModel.Faces[faceIndex].FaceRectangle);
            }

            // train the person group
            await _faceService.TrainPersonGroupAsync(_personGroupId);

            // wait until training is done
            TrainingStatus trainingStatus = null;

            while (true)
            {
                trainingStatus = await _faceService.GetPersonGroupTrainingStatusAsync(_personGroupId);

                if (trainingStatus.Status != Status.Running)
                {
                    break;
                }
                await Task.Delay(1000);
            }

            // remove from storage
            _storageService.Remove(key);
            return(Ok());
        }
Пример #27
0
        /// <summary>
        /// Asynchronously add face in oxford for a person and link it with a profile picture
        /// <see cref="PersonCreationFallBack(Guid?)"/>
        /// </summary>
        public async Task <bool> AddFaceToPersonInOxford(Person person, ProfilePicture picture, Face face, string temporaryImage)
        {
            Guid faceApiId = default(Guid);

            try
            {
                // if the person has reached the limit of 64 faces in oxford
                if (person.HasReachedMaxLimitOfFaces())
                {
                    await RemoveFaceFromOxford(person);
                }

                AddPersistedFaceResult result = await _faceServiceClient.AddPersonFaceAsync(Global.OxfordPersonGroupId,
                                                                                            person.PersonApiId, UrlHelpers.Content(Global.Host, temporaryImage), targetFace : face.FaceRectangle);

                faceApiId = result.PersistedFaceId;

                // Link profile picture with face on oxford api
                picture.FaceApiId = faceApiId;

                return(true);
            }
            catch (FaceAPIException e)
            {
                LogManager.GetLogger(GetType()).Info("Error occured during adding od face to person", e);

                // If is a new person we rollback its creation to avoid person without face
                if (person.Id == 0)
                {
                    await PersonCreationFallBack(person.PersonApiId);

                    File.Delete(MapPath(temporaryImage));
                    return(false);
                }

                return(true);
            }
        }
Пример #28
0
        private async void CreatePerson_Click(object sender, RoutedEventArgs e)
        {
            string name = textBox.Text;

            Console.WriteLine(name + " " + "added");

            // Define Anna
            CreatePersonResult friend1 = await faceServiceClient.CreatePersonAsync(
                // Id of the person group that the person belonged to
                personGroupId,
                // Name of the person
                name

                );

            var openDlg = new Microsoft.Win32.OpenFileDialog();

            openDlg.Filter = "JPEG Image(*.jpeg)|*.jpeg";
            bool?result = openDlg.ShowDialog(this);

            if (!(bool)result)
            {
                return;
            }

            string filePath = openDlg.FileName;



            using (Stream s = File.OpenRead(filePath))
            {
                // Detect faces in the image and add to Anna
                await faceServiceClient.AddPersonFaceAsync(
                    personGroupId, friend1.PersonId, s);
            }

            trainGroup();
        }
Пример #29
0
        public async Task <IActionResult> AddFace([FromBody] FaceUploadModel model)
        {
            var cursor = await _db.Persons.FindAsync(Builders <PersonDocument> .Filter.Eq(x => x.Id, model.UserID));

            var doc = await cursor.FirstAsync();

            var photo        = model.Photo.Substring(_imgPrefix.Length);
            var bytes        = Convert.FromBase64String(photo);
            var memoryStream = new MemoryStream(bytes);
            var result       = await _faceClient.AddPersonFaceAsync(_personGroupKey, doc.PersonId, memoryStream /*, null, targetFace */);

            var face = new FaceDocument()
            {
                Id              = ObjectId.GenerateNewId().ToString(),
                UserId          = doc.Id,
                ImageBase64     = photo,
                PersonId        = doc.PersonId,
                PersistedFaceId = result.PersistedFaceId,
                Created         = DateTime.Now
            };

            _db.Faces.InsertOneAsync(face);
            return(this.Json(doc));
        }
Пример #30
0
        ////통신
        //public static void sendImage()
        //{
        //    //클라이언트 소켓 생성
        //    Socket mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //    System.Diagnostics.Debug.WriteLine("소켓생성성공");
        //    //서버와 연결
        //    String IP = "192.168.24.233";
        //    mySocket.Connect(IP, 11111);
        //    System.Diagnostics.Debug.WriteLine("소켓생성성공");
        //    //파일의 엶
        //    String name = webCam.GetImageName();
        //    System.Diagnostics.Debug.WriteLine("파일열기성공");
        //    FileStream fileStr = new FileStream(name, FileMode.Open, FileAccess.Read);
        //    //파일 크기를 가져옴
        //    int fileLength = (int)fileStr.Length;
        //    System.Diagnostics.Debug.WriteLine("파일크기 가져오기 성공");
        //    //파일크기를 서버에 전송하기 위해 바이트 배열로 변환
        //    byte[] buffer = BitConverter.GetBytes(fileLength);
        //    System.Diagnostics.Debug.WriteLine("변환성공");
        //    //파일을 보낼 횟수
        //    int count = fileLength / 1024 + 1;
        //    //파일을 읽기 위해 BinaryRead 객체 생성
        //    BinaryReader reader = new BinaryReader(fileStr);
        //    System.Diagnostics.Debug.WriteLine("객체 생성성공");

        //    //파일송신작업
        //    for(int i=0; i < count; i++)
        //    {
        //        //파일을 읽음
        //        buffer = reader.ReadBytes(1024);
        //        //읽은 파일을 서버로 전송
        //        mySocket.Send(buffer);
        //    }
        //    System.Diagnostics.Debug.WriteLine("서버전송성공");
        //    //종료작업
        //    reader.Close();
        //    mySocket.Close();
        //}
        //Define people for the person group and detect,add person
        private async Task CreatePersonGroup()
        {
            System.Diagnostics.Debug.WriteLine("그룹만들기 시작");
            //Call the Face API.
            try
            {
                await faceServiceClient.CreatePersonGroupAsync(personGroupId, "Approved_People");

                System.Diagnostics.Debug.WriteLine("그룹만들기");
                // Define Bill
                CreatePersonResult friend1 = await faceServiceClient.CreatePersonAsync(
                    //Id of the person group that the person belonged to
                    personGroupId,
                    // Name of the person
                    "Bill");

                System.Diagnostics.Debug.WriteLine("Bill 추가");
                //Define Clare
                CreatePersonResult friend2 = await faceServiceClient.CreatePersonAsync(
                    //Id of the person group that the person belonged to
                    personGroupId,
                    //Name of the person
                    "Clare");

                System.Diagnostics.Debug.WriteLine("Clare 추가");
                //Define 연경
                CreatePersonResult friend3 = await faceServiceClient.CreatePersonAsync(
                    //id of the person group that the person belonged to
                    personGroupId,
                    //name of the person
                    "YeonKyeong");

                System.Diagnostics.Debug.WriteLine("연경 추가");

                foreach (string imagePath in Directory.GetFiles(friend1ImagerDir, "*.jpg"))
                {
                    using (Stream s = File.OpenRead(imagePath))
                    {
                        await faceServiceClient.AddPersonFaceAsync(
                            personGroupId, friend1.PersonId, s);
                    }
                    System.Diagnostics.Debug.WriteLine("Bill에 얼굴추가");
                }//Bill

                foreach (string imagePath in Directory.GetFiles(friend2ImagerDir, "*.jpg"))
                {
                    using (Stream s = File.OpenRead(imagePath))
                    {
                        await faceServiceClient.AddPersonFaceAsync(
                            personGroupId, friend2.PersonId, s);
                    }
                    System.Diagnostics.Debug.WriteLine("Clare에 얼굴추가");
                }//Clare
                foreach (string imagePath in Directory.GetFiles(friend3ImagerDir, "*.jpg"))
                {
                    using (Stream s = File.OpenRead(imagePath))
                    {
                        await faceServiceClient.AddPersonFaceAsync(
                            personGroupId, friend3.PersonId, s);
                    }
                    System.Diagnostics.Debug.WriteLine("연경에 얼굴추가");
                }//연경
            }
            //Catch and display Face API errors.
            catch (FaceAPIException f)
            {
                MessageBox.Show(f.ErrorMessage, f.ErrorCode);
                System.Diagnostics.Debug.WriteLine("그룹만들기 FaceAPIException=" + f);
            }
            //Catch and display all other errors.
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Error");
                System.Diagnostics.Debug.WriteLine("그룹만들기 오류 Exception=" + e);
            }
        }