コード例 #1
0
        private async void btngetreg_Click(object sender, RoutedEventArgs e)
        {
            Person[] persons = await fClient.ListPersonsAsync("smartapp");

            foreach (Person person in persons)
            {
                lvpersons.Items.Add(person.Name);
            }
        }
        /// <summary>
        /// Function to retrieve all persons in the Face API service
        /// </summary>
        private async void GetPersons()
        {
            if (SelectedPersonGroup == null)
            {
                return;
            }

            Persons.Clear();

            try
            {
                Person[] persons = await _faceServiceClient.ListPersonsAsync(SelectedPersonGroup.PersonGroupId);

                if (persons == null || persons.Length == 0)
                {
                    StatusText = $"No persons found in {SelectedPersonGroup.Name}.";
                    return;
                }

                foreach (Person person in persons)
                {
                    Persons.Add(person);
                }
            }
            catch (FaceAPIException ex)
            {
                StatusText = $"Failed to get persons from {SelectedPersonGroup.Name}: {ex.ErrorMessage}";
            }
            catch (Exception ex)
            {
                StatusText = $"Failed to get persons from {SelectedPersonGroup.Name}: {ex.Message}";
            }
        }
コード例 #3
0
        private async void StartButton_Click(object sender, RoutedEventArgs e)
        {
            _faceClient = new FaceServiceClient(SubscriptionKey, SubscriptionEndpoint);
            _groupName  = PersonGroupNameTextBox.Text;
            _persons    = await _faceClient.ListPersonsAsync(_groupName);

            await StartCamera();
        }
コード例 #4
0
        public async Task <bool> AddPerson(string GroupID, string eid, List <Stream> FaceStreamList)
        {
            bool             success = false;
            PersonResultItem person  = new PersonResultItem {
                EnterpriseID = eid, PersonGroupId = GroupID
            };

            try
            {
                var personList = await faceServiceClient.ListPersonsAsync(ConstantsString.GroupId);

                var responsePerson = personList.FirstOrDefault(t => t.Name == eid);
                if (responsePerson != null)
                {
                    person.PersonId = responsePerson.PersonId;
                }
                else
                {
                    CreatePersonResult result = await faceServiceClient.CreatePersonAsync(person.PersonGroupId, person.EnterpriseID);

                    person.PersonId = result.PersonId;
                }

                if (person.PersonId != Guid.Empty)
                {
                    foreach (var faceStream in FaceStreamList)
                    {
                        await WaitCallLimitPerSecondAsync();

                        AddPersistedFaceResult result = await faceServiceClient.AddPersonFaceAsync(ConstantsString.GroupId, person.PersonId, faceStream);

                        success = result.PersistedFaceId != Guid.Empty;
                    }
                }
                else
                {
                    success = false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(success);
        }
コード例 #5
0
 internal async Task <Person[]> GetKnownPeople()
 {
     Person[] people = null;
     if (null != faceServiceClient)
     {
         people = await faceServiceClient.ListPersonsAsync(personGroupId);
     }
     return(people);
 }
コード例 #6
0
        static async Task ListEmployeesInGroup(string personGroupId)
        {
            var employees = await _faceServiceClient.ListPersonsAsync(personGroupId);

            Console.WriteLine("Listing everyone in the group Employees: ");
            foreach (Person person in employees)
            {
                Console.WriteLine("   Person Name: {0}, Person Id: {1}", person.Name, person.PersonId);
            }
        }
コード例 #7
0
        /// <summary>
        /// Create UI buttons for the Person's in the group
        /// </summary>
        /// <param name="group">An optional <c>PersonGroup</c> object.</param>
        /// <param name="people">An optional <c>Person</c> list.</param>
        /// <remarks>
        /// <para>Both parameters are optional, BUT at least one must be provided</para>
        /// </remarks>
        private async void AddPersonButtons(PersonGroup group = null, Person[] people = null)
        {
            //Reset the UI elements including the buttons
            btns.Children.Clear();
            InfoHeaderTextBlock.Text = "";

            if (null != group || null != people)
            {
                //Set people ONLY if the group was sent but NOT the people
                if (null != group && null == people)
                {
                    //Prep API Call
                    await ApiCallAllowed(true);

                    faceServiceClient = new FaceServiceClient(authKey);
                    people            = await faceServiceClient.ListPersonsAsync(group.PersonGroupId);
                }

                if (people.Count() <= 50)
                {
                    foreach (var p in people)
                    {
                        //UWP button object
                        Button newButton = new Button
                        {
                            Content = p.Name,
                            Margin  = new Thickness(20, 5, 10, 10),
                            Height  = 50,
                            Width   = 200,
                        };
                        newButton.Click += SelectPerson_Click;
                        btns.Children.Add(newButton);
                    }
                }
                else
                {
                    btns.Children.Clear();
                    string peopleText = "";
                    foreach (var p in people)
                    {
                        peopleText += "\n\r" + p.Name;
                    }
                    JSONTextBlock.Text = peopleText;
                }

                InfoHeaderTextBlock.Text = "People In " + knownGroup.Name + ":";
            }
            else
            {
                InfoHeaderTextBlock.Text = "There seems to be a problem with the Group";
            }
        }
コード例 #8
0
        /// <summary>
        /// This method creates a new person if it doesn't exist yet within the Face API, and uses its newly created person ID as its name.
        /// </summary>
        /// <param name="name">The name of the person to create: can either be a real name when updating a person, or a temporary GUID for a newly found person.</param>
        /// <returns>The final person ID of the Face API created person, or the ID of the person with this name that already existed.</returns>
        public async Task <Guid> CreatePerson(string name)
        {
            var persons = await faceServiceClient.ListPersonsAsync(personGroupId);

            var result = persons.Where(p => p.Name == name).ToList();

            if (result.Any())
            {
                // if the person exists, update its name with the possible new value
                var person = result.FirstOrDefault();
                return(person.PersonId);
            }

            // if the person doesn't exist, create him or her
            var createPersonResult = await faceServiceClient.CreatePersonAsync(personGroupId, name);

            // now update the name with its Face API person ID (because we do not yet know the name of newly found persons)
            var newName = createPersonResult.PersonId.ToString();
            await faceServiceClient.UpdatePersonAsync(personGroupId, createPersonResult.PersonId, newName);

            return(createPersonResult.PersonId);
        }
コード例 #9
0
        public static async Task <IdentifiedFace> CheckGroupAsync(FaceServiceClient faceClient, Stream stream, string personGroupId, string groupImagesFolder)
        {
            try
            {
                var response = await FaceApiHelper.IdentifyPersonAsync(faceClient, stream, personGroupId);

                if (response?.Candidates == null || response.Candidates.Length == 0)
                {
                    return(null);
                }

                // Due to legal limitations, Face API does not support images retrieval in any circumstance currently.You need to store the images and maintain the relationship between face ids and images by yourself.
                var personsFolder = await PicturesHelper.GetPersonFolderAsync(groupImagesFolder);

                var dataSet = await faceClient.ListPersonsAsync(personGroupId);

                var matches =
                    from c in response.Candidates
                    join p in dataSet on c.PersonId equals p.PersonId into ps
                    from p in ps.DefaultIfEmpty()
                    select new IdentifiedFace
                {
                    Confidence = c.Confidence,
                    PersonName = p == null ? "(No matching face)" : p.Name,
                    FaceId     = c.PersonId
                };

                var match = matches.OrderByDescending(m => m.Confidence).FirstOrDefault();


                if (match == null)
                {
                    return(null);
                }

                var matchFile = await personsFolder.GetFileAsync($"{match.PersonName}.{Constants.LocalPersonFileExtension}");

                IRandomAccessStream photoStream = await matchFile.OpenReadAsync();

                match.FaceStream = photoStream.CloneStream().AsStream();
                return(match);
            }
            catch (Exception)
            {
                return(null);
            }
        }
コード例 #10
0
        private async void cmbPersonGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            string groupID = ((PersonGroup)(cmbPersonGroup.Items[cmbPersonGroup.SelectedIndex])).PersonGroupId;

            //string groupID = cmbPersonGroup.SelectedItem.ToString();
            if (groupID != null)
            {
                Person[] people = await _faceClient.ListPersonsAsync(groupID);

                cmbPersonName.Items.Clear();

                for (int i = 0; i < people.Length; i++)
                {
                    cmbPersonName.Items.Add(people[i].Name);
                }
            }
        }
コード例 #11
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            string roll = Roll.Text;
            Guid   value;

            Person[] y;
            //Person d = null;
            int p = -1;

            y = await faceServiceClient.ListPersonsAsync("student");

            for (int i = 0; i < y.Length; i++)
            {
                if (y[i].Name == roll)
                {
                    p     = 0;
                    value = y[i].PersonId;
                    // d = y[i];
                    break;
                }
            }
            if (p == -1)
            {
                Roll.Text = "Cannot delete as given roll number does not exist";
            }
            else
            {
                /*if (d == null)
                 *  return;
                 *
                 * for(int i =0; i < d.PersistedFaceIds.Length; i++)
                 * {
                 *  await faceServiceClient.DeleteFaceFromFaceListAsync(d.Name, d.PersistedFaceIds[i]);
                 * }*/

                await faceServiceClient.DeletePersonAsync("student", value);

                Roll.Text = "Deleted Successfully";
            }
        }
コード例 #12
0
ファイル: GenLib.cs プロジェクト: eumarassis/Image_analyzer
        public static async Task <string> AddFace(MemoryStream faceStream, string personName, string groupId, string groupDisplayName, FaceServiceClient FaceClient, bool showMsgBox = true)
        {
            string statusStr;

            try
            {
                // Does PersonGroup already exist
                try
                {
                    await FaceClient.GetPersonGroupAsync(groupId);
                }
                catch (Exception)
                {
                    // person group does not exist - create it
                    await FaceClient.CreatePersonGroupAsync(groupId, groupDisplayName);

                    // FIX there needs to be a wait or something to detect the new personGroup
                    await FaceClient.GetPersonGroupAsync(groupId);
                }
                //Get list of faces if any
                Person[] people = await FaceClient.ListPersonsAsync(groupId);

                Person p = people.FirstOrDefault(myP => myP.Name.Equals(personName, StringComparison.OrdinalIgnoreCase));
                Guid   personId;
                if (p != null)
                {
                    // person already exists - train our model to include new picture
                    personId = p.PersonId;
                }
                else
                {
                    // personGroupId is the group to add the person to, personName is what the user typed in to identify this face
                    CreatePersonResult myPerson = await FaceClient.CreatePersonAsync(groupId, personName);

                    personId = myPerson.PersonId;
                }
                // Person - List Persons in a Person Group
                // Detect faces in the image and add
                await FaceClient.AddPersonFaceAsync(groupId, personId, faceStream);

                // whenever we add a face, docs says we need to retrain - do it!

                //await retrainPersonGroup(_options.PersonGroupId);

                //// I think this is needed
                await FaceClient.TrainPersonGroupAsync(groupId);

                while (true)
                {
                    TrainingStatus trainingStatus = await FaceClient.GetPersonGroupTrainingStatusAsync(groupId);

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

                    await Task.Delay(1000);
                }

                statusStr = $@"A new face with name '{personName}' has been added and / or trained successfully in the personGroup '{groupId}'";

                //await UpdatePersonListAsync();
                //await _frmMain.UpdatePersonListAsync();
            }
            catch (Exception ex)
            {
                statusStr = $@"Unhandled excpetion while trying to add face: {ex.Message}";
            }

            if (showMsgBox)
            {
                MessageBox.Show(statusStr);
            }
            return(statusStr);
        }
コード例 #13
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            Roll.Text = "Roll no.(s) of Identified Persons: ";
            VisualizationCanvas.Children.Clear();
            FileOpenPicker photoPicker = new FileOpenPicker();

            photoPicker.ViewMode = PickerViewMode.Thumbnail;
            photoPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            photoPicker.FileTypeFilter.Add(".jpg");
            photoPicker.FileTypeFilter.Add(".jpeg");
            photoPicker.FileTypeFilter.Add(".png");
            photoPicker.FileTypeFilter.Add(".bmp");

            StorageFile photoFile = await photoPicker.PickSingleFileAsync();

            if (photoFile == null)
            {
                return;
            }
            string filePath = photoFile.Path;

            using (var stream = await photoFile.OpenAsync(FileAccessMode.Read))
            {
                var faces = await faceServiceClient.DetectAsync(stream.AsStream());

                var faceIds = faces.Select(face => face.FaceId).ToArray();
                var results = await faceServiceClient.IdentifyAsync("student", faceIds);

                foreach (var identifyResult in results)
                {
                    //Console.WriteLine("Result of face: {0}", identifyResult.FaceId);
                    if (identifyResult.Candidates.Length == 0)
                    {
                        string s = Roll.Text;
                        Roll.Text = s + "Not identified, ";
                    }
                    else
                    {
                        // Get top 1 among all candidates returned
                        Person[] x = await faceServiceClient.ListPersonsAsync("student");

                        Candidate name        = identifyResult.Candidates[0];
                        var       candidateId = name.PersonId;
                        int       p           = 0;
                        for (int i = 0; i < x.Length; i++)
                        {
                            if (x[i].PersonId == candidateId)
                            {
                                p = 1;
                                break;
                            }
                        }
                        if (p == 0)
                        {
                            Roll.Text = Roll.Text + " Not identified, ";
                            continue;
                        }
                        var person = await faceServiceClient.GetPersonAsync("student", candidateId);

                        string s = Roll.Text;
                        Roll.Text = s + person.Name + ", ";
                        string   day   = DateTime.Today.Day.ToString();
                        string   month = DateTime.Today.Month.ToString();
                        string   year  = DateTime.Today.Year.ToString();
                        string   date  = month + "/" + day + "/" + year;
                        TodoItem item  = new TodoItem {
                            Roll = person.Name,
                            Date = date
                        };
                        await MobileService.GetTable <TodoItem>().InsertAsync(item);
                    }
                }

                BitmapImage bitmapSource = new BitmapImage();

                IRandomAccessStream fileStream = await photoFile.OpenAsync(FileAccessMode.Read);

                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

                BitmapTransform transform = new BitmapTransform();
                const float     sourceImageHeightLimit = 1280;

                if (decoder.PixelHeight > sourceImageHeightLimit)
                {
                    float scalingFactor = (float)sourceImageHeightLimit / (float)decoder.PixelHeight;
                    transform.ScaledWidth  = (uint)Math.Floor(decoder.PixelWidth * scalingFactor);
                    transform.ScaledHeight = (uint)Math.Floor(decoder.PixelHeight * scalingFactor);
                }

                SoftwareBitmap sourceBitmap = await decoder.GetSoftwareBitmapAsync(decoder.BitmapPixelFormat, BitmapAlphaMode.Premultiplied, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);

                const BitmapPixelFormat faceDetectionPixelFormat = BitmapPixelFormat.Gray8;

                SoftwareBitmap convertedBitmap;

                if (sourceBitmap.BitmapPixelFormat != faceDetectionPixelFormat)
                {
                    convertedBitmap = SoftwareBitmap.Convert(sourceBitmap, faceDetectionPixelFormat);
                }
                else
                {
                    convertedBitmap = sourceBitmap;
                }

                SolidColorBrush lineBrush     = new SolidColorBrush(Windows.UI.Colors.Yellow);
                double          lineThickness = 2.0;
                SolidColorBrush fillBrush     = new SolidColorBrush(Windows.UI.Colors.Transparent);

                ImageBrush           brush        = new ImageBrush();
                SoftwareBitmapSource bitmapsource = new SoftwareBitmapSource();
                await bitmapsource.SetBitmapAsync(sourceBitmap);

                brush.ImageSource = bitmapsource;
                brush.Stretch     = Stretch.Fill;
                this.VisualizationCanvas.Background = brush;
                double widthScale  = sourceBitmap.PixelWidth / this.VisualizationCanvas.ActualWidth;
                double heightScale = sourceBitmap.PixelHeight / this.VisualizationCanvas.ActualHeight;

                foreach (var face in faces)
                {
                    // Create a rectangle element for displaying the face box but since we're using a Canvas
                    // we must scale the rectangles according to the image’s actual size.
                    // The original FaceBox values are saved in the Rectangle's Tag field so we can update the
                    // boxes when the Canvas is resized.
                    Rectangle box = new Rectangle
                    {
                        Tag             = face.FaceRectangle,
                        Width           = (uint)(face.FaceRectangle.Width / widthScale),
                        Height          = (uint)(face.FaceRectangle.Height / heightScale),
                        Fill            = fillBrush,
                        Stroke          = lineBrush,
                        StrokeThickness = lineThickness,
                        Margin          = new Thickness((uint)(face.FaceRectangle.Left / widthScale), (uint)(face.FaceRectangle.Top / heightScale), 0, 0)
                    };
                    this.VisualizationCanvas.Children.Add(box);
                }
            }
        }
コード例 #14
0
        private async void GroupTest()
        {
            var photodir = await KnownFolders.PicturesLibrary.GetFileAsync(PHOTO_FILE_NAME);

            string photo = photodir.Path;

            string picdir = photo.Substring(0, photo.Length - 9);



            try
            {
                await faceServiceClient.CreatePersonGroupAsync(personGroupId, "FaceGroup");


                //tbl_status.Text = "Group created";
            }
            catch
            {
                //tbl_status.Text = "Group exists";
            }

            try
            {
                var persons = await faceServiceClient.ListPersonsAsync(personGroupId);

                foreach (var person in persons)
                {
                    if (person.PersistedFaceIds.Count() == 0)
                    {
                        personlist.Add(person.PersonId.ToString());
                    }
                }
                var lists = personlist;
                for (int i = 0; i < personlist.Count; i++)
                {
                    await faceServiceClient.DeletePersonAsync(personGroupId, Guid.Parse(personlist[i]));
                }
                await faceServiceClient.TrainPersonGroupAsync(personGroupId);

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

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

                    await Task.Delay(1000);
                }


                string testImageFile = photo;



                using (Stream s = File.OpenRead(await GetPhoto()))
                {
                    var faces = await faceServiceClient.DetectAsync(s, returnFaceLandmarks : true,
                                                                    returnFaceAttributes : requiredFaceAttributes);

                    foreach (var faceinfo in faces)
                    {
                        var id          = faceinfo.FaceId;
                        var attributes  = faceinfo.FaceAttributes;
                        var age         = attributes.Age;
                        var gender      = attributes.Gender;
                        var smile       = attributes.Smile;
                        var facialHair  = attributes.FacialHair;
                        var headPose    = attributes.HeadPose;
                        var glasses     = attributes.Glasses;
                        var emotion     = attributes.Emotion;
                        var emotionlist = emotion;
                        int i           = 0;
                        int max         = 0;

                        /*foreach (var kvp in emotionlist.ToRankedList())
                         * {
                         *  if(kvp.Value > max)
                         *  {
                         *      maxemotion = i;
                         *  }
                         *  object[] item = new object[2];
                         *  item[0] = kvp.Key;
                         *  item[1] = kvp.Value;
                         *  i++;
                         * }
                         * Infostring = "Mood: " + list[maxemotion][0].ToString();*/
                        // emo = emotionlist.Max().Value;
                        // emotionstring = emotion.Happiness.ToString();
                        if (glasses.ToString().ToUpper() != "NOGLASSES")
                        {
                            activeId += " Gleraugnaglámur";
                        }
                        Infostring = "ID: " + id.ToString() + "," + "Age: " + age.ToString() + "," + "Gender: " + gender.ToString() + "," + "Glasses: " + glasses.ToString();
                    }

                    //emo.ToString();

                    var faceIds = faces.Select(face => face.FaceId).ToArray();
                    var results = await faceServiceClient.IdentifyAsync(personGroupId, faceIds);


                    foreach (var identifyResult in results)
                    {
                        //  tbl_status.Text = ("Result of face: " + identifyResult.FaceId);
                        if (identifyResult.Candidates.Length == 0)
                        {
                            //tbl_status.Text = ("No one identified, i will add you now, your new name is Bill");
                            CreatePersonResult friend1 = await faceServiceClient.CreatePersonAsync(
                                // Id of the person group that the person belonged to
                                personGroupId,
                                // Name of the person
                                "Hlini"
                                );

                            for (int z = 0; z < 6; z++)
                            {
                                Random r = new Random();
                                photostorage = await KnownFolders.PicturesLibrary.CreateFileAsync((z + PHOTO_FILE_NAME), CreationCollisionOption.ReplaceExisting);

                                ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
                                await mediaCapture.CapturePhotoToStorageFileAsync(imageProperties, photostorage);

                                var friend1ImageDir = await KnownFolders.PicturesLibrary.GetFileAsync(z + PHOTO_FILE_NAME);

                                string imagePath = friend1ImageDir.Path;

                                using (Stream k = File.OpenRead(imagePath))
                                {
                                    await faceServiceClient.AddPersonFaceAsync(
                                        personGroupId, friend1.PersonId, k);
                                }
                            }


                            await faceServiceClient.TrainPersonGroupAsync(personGroupId);

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

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

                                await Task.Delay(1000);
                            }
                            Task t = Task.Run(() => { CheckFace(); });
                        }
                        else
                        {
                            // Get top 1 among all candidates returned
                            var candidateId = identifyResult.Candidates[0].PersonId;
                            var person      = await faceServiceClient.GetPersonAsync(personGroupId, candidateId);

                            //tbl_status.Text = ("Identified as " + person.Name);
                            //activeId = person.Name.ToString();
                            //await faceServiceClient.UpdatePersonAsync(personGroupId, person.PersonId, "Ólafur Jón");
                            activeId = person.Name.ToString();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                activeId = "Main: " + activeId + " " + Infostring;
            }
        }
コード例 #15
0
 public async Task <Person[]> GetPersonsAsync(string personGroupId)
 {
     return(await faceClient.ListPersonsAsync(personGroupId));
 }
コード例 #16
0
        static async void AddFaceIntoPersonGroup(FaceServiceClient faceCli)
        {
            inputMode = false;

            Console.WriteLine(":Add face:");
            Console.WriteLine(":Enter the path to an image with faces that you wish to analzye: ");
            Console.Write("$ ");
            //string imageFilePath = "c:\\temp\\smithm1.jpg";

            string imageFilePath = Console.ReadLine();

            try
            {
                using (Stream s = File.OpenRead(imageFilePath))
                {
                    Console.WriteLine(":Enter the person name");
                    string personName = Console.ReadLine();
                    var    persons    = await faceCli.ListPersonsAsync(personName);

                    Guid personid;
                    foreach (var person in persons)
                    {
                        if (person.Name == personName)
                        {
                            personid = person.PersonId;
                        }
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("Group Id: " + person.PersonId);
                        Console.ForegroundColor = ConsoleColor.Gray;
                        await faceCli.AddPersonFaceAsync(personName, person.PersonId, s);

                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("Add " + personName + " face completed");
                        Console.ForegroundColor = ConsoleColor.Gray;
                    }

                    //await Task.Delay(1000);

                    await faceCli.TrainPersonGroupAsync(personName);

                    TrainingStatus trainingStatus = null;
                    while (true)
                    {
                        trainingStatus = await faceCli.GetPersonGroupTrainingStatusAsync(personName);

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

                        await Task.Delay(1000);
                    }

                    inputMode = true;
                    paintMenu();
                }
            }
            catch (Exception ex)
            {
                inputMode = true;
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
                paintMenu();
            }



            // Execute the REST API call.
            // MakeAnalysisRequest(imageFilePath);
        }
コード例 #17
0
        public async Task <IList <Person> > GetAll(string personGroupId)
        {
            var persons = await _faceServiceClient.ListPersonsAsync(personGroupId);

            return(persons);
        }
コード例 #18
0
 public async Task <IList <Person> > GetKnownPersons()
 {
     return(await faceClient.ListPersonsAsync(PersonGroup));
 }
コード例 #19
0
        private async void ButtonClick(object sender, RoutedEventArgs e)
        {
            string roll = Roll.Text;

            if (Roll.Text.Length == 0)
            {
                Roll.PlaceholderText = "Enter roll number first";
                return;
            }
            FileOpenPicker photoPicker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.PicturesLibrary
            };

            photoPicker.FileTypeFilter.Add(".jpg");
            photoPicker.FileTypeFilter.Add(".jpeg");
            photoPicker.FileTypeFilter.Add(".png");
            photoPicker.FileTypeFilter.Add(".bmp");

            StorageFile photoFile = await photoPicker.PickSingleFileAsync();

            if (photoFile == null)
            {
                return;
            }

            string filePath = photoFile.Path;

            PersonGroup[] x = await faceServiceClient.ListPersonGroupsAsync();

            int  p = -1;
            Guid value;

            Person[]           y;
            CreatePersonResult friend1;

            y = await faceServiceClient.ListPersonsAsync("student");

            for (int i = 0; i < y.Length; i++)
            {
                if (y[i].Name == roll)
                {
                    p = i;
                    break;
                }
            }
            if (p == -1)
            {
                friend1 = await faceServiceClient.CreatePersonAsync("student", roll);

                value = friend1.PersonId;
            }
            else
            {
                value = y[p].PersonId;
            }
            //using (Stream s = File.OpenRead(filePath)) // thsi statement doesn't work in windows UWP. It works only on windows desktop applications and console apps.
            using (var stream = await photoFile.OpenAsync(FileAccessMode.Read))
            {
                await faceServiceClient.AddPersonFaceAsync("student", value, stream.AsStream());
            }
            await faceServiceClient.TrainPersonGroupAsync("student");

            try
            {
                while (true)
                {
                    TrainingStatus trainingStatus = await faceServiceClient.GetPersonGroupTrainingStatusAsync("student");

                    Roll.Text = trainingStatus.Status.ToString();
                    if (trainingStatus.Status != Status.Running)
                    {
                        break;
                    }
                    await Task.Delay(1000);
                }
            }
            catch (Exception ex)
            {
                Roll.Text = ex.Message;
            }
        }
コード例 #20
0
        /// <summary>
        ///     撮影する
        /// </summary>
        private async void _Shot()
        {
            // カメラで撮影(ローカルに保存)
            var folder = ApplicationData.Current.TemporaryFolder;
            var file   = await folder.CreateFileAsync("temp.jpg", CreationCollisionOption.ReplaceExisting);

            await _cameraHelper.MediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), file);

            try
            {
                // Face APIクライアントを生成
                var client = new FaceServiceClient(Constants.FACE_KEY, Constants.FACE_ENDPOINT);

                var loader = new ResourceLoader();
                // 認識した顔の数をチェックする
                Face[] f;
                using (var stream = File.OpenRead(file.Path))
                {
                    f = await client.DetectAsync(stream, false);
                }
                if (f.Length == 0)
                {
                    var dialog = new MessageDialog(loader.GetString("NO_FACES"));
                    await dialog.ShowAsync();

                    return;
                }

                // ユーザ情報を追加/更新
                var name    = txtName.Text.Trim();
                var persons = await client.ListPersonsAsync(Constants.TARGET_GROUP);

                var person = persons.FirstOrDefault(p => p.Name == name);
                if (person == null)
                {
                    // 追加処理 Azure Cognitiveサービスにユーザ情報を追加
                    var result = await client.CreatePersonAsync(Constants.TARGET_GROUP, name, "");

                    person = new Person {
                        Name = name, UserData = "", PersonId = result.PersonId
                    };
                    // 追加処理 Azure Cognitiveサービスに画像ファイルをアップロードし学習
                    using (var stream = File.OpenRead(file.Path))
                    {
                        var faceResult = await client.AddPersonFaceAsync(Constants.TARGET_GROUP, result.PersonId, stream);

                        person.PersistedFaceIds = new[] { faceResult.PersistedFaceId };
                    }
                    // ユーザグループ情報を更新
                    await client.TrainPersonGroupAsync(Constants.TARGET_GROUP);
                }
                else
                {
                    // ユーザ情報の更新 Azure Cognitiveサービスに画像ファイルをアップロードし学習
                    if (!string.IsNullOrEmpty(file.Path))
                    {
                        using (var stream = File.OpenRead(file.Path))
                        {
                            var faceResult =
                                await client.AddPersonFaceAsync(Constants.TARGET_GROUP, person.PersonId, stream);

                            person.PersistedFaceIds
                                = person.PersistedFaceIds.Concat(new[] { faceResult.PersistedFaceId }).ToArray();
                        }
                    }
                }
                var message = new MessageDialog(loader.GetString("MSG_COMPLETE"));
                await message.ShowAsync();
            }
            catch (FaceAPIException e)
            {
                var dialog = new MessageDialog(e.ErrorMessage);
                await dialog.ShowAsync();
            }
            catch (Exception e)
            {
                var dialog = new MessageDialog(e.Message);
                await dialog.ShowAsync();
            }
        }