private async Task TrainIt(IProgress <string> progress) { progress.Report("Creating Person Group"); var key = ConfigurationManager.AppSettings["subscriptionKey"]; var apiRoot = ConfigurationManager.AppSettings["apiRoot"]; var faceServiceClient = new FaceServiceClient(key, apiRoot); var samplesDir = ConfigurationManager.AppSettings["samplesDir"]; string personGroupId = "test-group"; try { await faceServiceClient.DeletePersonGroupAsync(personGroupId); } catch (Exception ex) { progress.Report($"Delete Person Group Error: {ex.Message}"); } try { await faceServiceClient.CreatePersonGroupAsync(personGroupId, "Test Group"); } catch (Exception ex) { progress.Report($"Create Person Group Error: {ex.Message}"); } var personGroupDir = System.IO.Path.Combine(samplesDir, "PersonGroup"); DirectoryInfo di = new DirectoryInfo(personGroupDir); var personDirectories = di.GetDirectories(); foreach (var personDirectory in personDirectories) { string personName = personDirectory.Name; progress.Report($"Adding '{personName}'"); CreatePersonResult person = await faceServiceClient.CreatePersonAsync( // group id personGroupId, // person name personName); foreach (var image in personDirectory.GetFiles("*.jpg")) { using (Stream s = File.OpenRead(image.FullName)) { await faceServiceClient.AddPersonFaceAsync( personGroupId, person.PersonId, s); } } } progress.Report("Training Person Group"); await faceServiceClient.TrainPersonGroupAsync(personGroupId); TrainingStatus trainingStatus = null; while (true) { trainingStatus = await faceServiceClient.GetPersonGroupTrainingStatusAsync(personGroupId); var status = trainingStatus.Status.ToString().ToLower(); if (status != "running") { break; } await Task.Delay(1000); } progress.Report("Upload image for identification"); string testImageFile = System.IO.Path.Combine(samplesDir, @"identification3.jpg"); 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) { progress.Report($"Result of face: {identifyResult.FaceId}"); if (identifyResult.Candidates.Length == 0) { progress.Report("No one identified"); } else { // Get top 1 among all candidates returned var candidateId = identifyResult.Candidates[0].PersonId; var person = await faceServiceClient.GetPersonAsync(personGroupId, candidateId); progress.Report($"Identified as {person.Name}"); } } } progress.Report("Done"); }
private async void button1_Click(object sender, RoutedEventArgs e) { personGroupId = "1"; try { await faceServiceClient.DeletePersonGroupAsync(personGroupId); } catch (Microsoft.ProjectOxford.Face.FaceAPIException exc) { Debug.WriteLine(exc.ErrorCode); } try { await faceServiceClient.CreatePersonGroupAsync(personGroupId, "PG"); } catch (Microsoft.ProjectOxford.Face.FaceAPIException exc) { Debug.WriteLine(exc.ErrorCode); } String[] listOfPersons = { "person1" }; CreatePersonResult[] person = new CreatePersonResult[listOfPersons.Length]; string[] personImageDir = new string[listOfPersons.Length]; for (int i = 0; i < listOfPersons.Length; i++) { person[i] = await faceServiceClient.CreatePersonAsync(personGroupId, listOfPersons[i]); FolderPicker folderPicker = new FolderPicker(); folderPicker.FileTypeFilter.Add(".jpg"); folderPicker.FileTypeFilter.Add(".jpeg"); folderPicker.FileTypeFilter.Add(".png"); folderPicker.FileTypeFilter.Add(".bmp"); folderPicker.ViewMode = PickerViewMode.Thumbnail; StorageFolder photoFolder = await folderPicker.PickSingleFolderAsync(); if (photoFolder == null) { return; } var files = await photoFolder.GetFilesAsync(); foreach (var file in files) { var inputStream = await file.OpenReadAsync(); Stream stream = inputStream.AsStreamForRead(); await faceServiceClient.AddPersonFaceAsync(personGroupId, person[i].PersonId, stream); } } await faceServiceClient.TrainPersonGroupAsync(personGroupId); TrainingStatus trainingStatus = null; while (true) { trainingStatus = await faceServiceClient.GetPersonGroupTrainingStatusAsync(personGroupId); if (!trainingStatus.Status.Equals("running")) { break; } await Task.Delay(1000); } }
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); }
public async Task <CreatePersonResult> InsertPerson(ICallistoInsertOne <Person> insertOne) { await Operators.Insert.One(insertOne); return(CreatePersonResult.Create(insertOne.Value.Id)); }
static async void CreatePerson() { FaceServiceClient faceServiceClient = new FaceServiceClient(subscriptionKey.ToString(), "https://northeurope.api.cognitive.microsoft.com/face/v1.0/"); string personGroupId = "facegroup"; string name = null; string reply = null; FolderBrowserDialog folder = new FolderBrowserDialog(); Console.WriteLine("HOW TO:\nWhen you press Enter I will ask for name, that name should be the name of the person you want to link to the face API Better type it right cause i wont ask if it's spelled right."); Console.WriteLine("After name has been entered i will make you choose a directory where photos are kept"); Console.WriteLine("Since this is a free trial i will only take a look at the first five photos."); Console.WriteLine("For Optimal recognition please only use photos where the person is alone."); while (reply != "exit") { Console.WriteLine("OK Type begin to start"); if (Console.ReadLine().ToLower() == "begin") { Console.WriteLine("Insert The Person's Name"); name = Console.ReadLine(); if (name == "" || name == null) { Console.WriteLine("Please write a valid name..."); } else { Console.WriteLine("Choose a folder"); string folderpath = null; DialogResult result = folder.ShowDialog(); if (result == DialogResult.OK) { folderpath = folder.SelectedPath; } else { Console.Write("You have Cancelled the action"); } try { using (Stream s = File.OpenRead((Directory.GetFiles(folderpath, "*.jpg")[0]))) { 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) { Console.WriteLine("Result of face: {0}", identifyResult.FaceId); if (identifyResult.Candidates.Length == 0) { CreatePersonResult friend1 = await faceServiceClient.CreatePersonAsync( // Id of the person group that the person belonged to personGroupId, // Name of the person name ); for (int i = 0; i < 6; i++) { string imagePath = Directory.GetFiles(folderpath, "*.jpg")[i]; using (Stream k = File.OpenRead(imagePath)) { // Detect faces in the image and add to Anna await faceServiceClient.AddPersonFaceAsync( personGroupId, friend1.PersonId, k); Console.WriteLine("Adding Picture " + i + 1 + " to the face of " + name); } } TrainingStatus trainingStatus = null; Console.WriteLine("Starting Group Training Process"); while (true) { trainingStatus = await faceServiceClient.GetPersonGroupTrainingStatusAsync(personGroupId); Console.WriteLine(trainingStatus.Status.ToString()); if (trainingStatus.Status.ToString() != "running") { break; } await Task.Delay(3000); } } else { // Get top 1 among all candidates returned var candidateId = identifyResult.Candidates[0].PersonId; var person = await faceServiceClient.GetPersonAsync(personGroupId, candidateId); Console.WriteLine("Looks Like Your friend is already here under the name {0} i am {1} confident", person.Name, identifyResult.Candidates[0].Confidence); } } } } catch (Exception e) { Console.Write("Error at: " + e.Message); } } } Console.WriteLine("\nto quit type exit or just quit, to go again press enter"); } Console.ReadLine(); }
// Robin Added :Now you are ready to call the Face API from your application. /// <summary> ////////////// /// Button click triggers Create a group, add friends to that group, bind photos to each person /// </summary> // --------- Robin Added for the _Click ----------------- public async void BrowseButton_Click1(object sender, RoutedEventArgs e) { // ====================================================================================================================== /* * // Decalare Variables * bool groupExists = false; * * // Below is to open a Dialog to get the file name, pop up the dialog box: openDlg.ShowDialog(this); * // Eventually skip the open dialog, and just go read the files directly * var openDlg = new Microsoft.Win32.OpenFileDialog(); * * openDlg.Filter = "JPEG Image(*.jpg)|*.jpg"; * bool? result = openDlg.ShowDialog(this); * * if (!(bool)result) * { * return; * } * */ /* * // Step 1 : getting those photos directories and its photo * // hard code the root folder for all image sub folder, it starts in this folder and search down : * // C:\Users\v-role\Desktop\TestPhotos\SingleImage\ * // store the file name * string filePath = openDlg.FileName; // filePath is the image file name, I want to skip this method * * // example to get its folder name * FileInfo fInfo = new FileInfo(filePath); * String FolderName = fInfo.Directory.Name; * * * * // example to get the Full path of that file * String tmprootFolderName = System.IO.Path.GetDirectoryName(filePath); // this is the root folder * System.IO.DirectoryInfo rootFolderName = new System.IO.DirectoryInfo(tmprootFolderName); // this is the root folder * * * myoutputBox.Text += "Folder Name = "+ FolderName + " File Name = "+ filePath+ " \n"; * myoutputBox.Text += "Root Folder Name = " + tmprootFolderName + " File Name = " + filePath + " \n"; */ /* * ////////////////////// group creation * * // Step 2 : Test whether the group already exists * try * { * myoutputBox.Text += "* Request: GroupID : " + GroupName + " will be used for build person database. \n Checking whether group " + GroupName + " exists...\n"; * * await faceServiceClient.GetPersonGroupAsync(GroupName); * * groupExists = true; * myoutputBox.Text += "* Response: Group " + GroupName + " exists. \n"; * } * catch (FaceAPIException ex) * { * if (ex.ErrorCode != "PersonGroupNotFound") * { * myoutputBox.Text += "* Response: " + ex.ErrorCode + " : " + ex.ErrorMessage + "\n"; * return; * } * else * { * myoutputBox.Text += "* Response: GroupID " + GroupName + " does not exist before. \n"; * } * } * * // Well, if that GroupID already exist, first Delete it * if (groupExists) * { * myoutputBox.Text += "* Response: GroupID " + GroupName + " exists before. We are deleting it to start a new Group ID\n"; * await faceServiceClient.DeletePersonGroupAsync(GroupName); * } * * else // group not exist, use the new groupId to create the new group, usually this is the case. * { * // Call create person group REST API * // Create person group API call will failed if group with the same name already exists * myoutputBox.Text += "* Request: Creating group with GroupID " + GroupName + " \n"; * try * { * await faceServiceClient.CreatePersonGroupAsync(GroupName, GroupName); * myoutputBox.Text += "* Response: Success. Group ID " + GroupName + " created \n"; * } * catch (FaceAPIException ex) * { * myoutputBox.Text += "* Response: " + ex.ErrorCode + " : " + ex.ErrorMessage + "\n"; * * return; * } * * ////////////////////// End group creation * } * * */ // ====================================================================================================================== myoutputBox.Text += " A Moment Please ... \n"; System.Threading.Thread.Sleep(5000); // Create an empty person group // string personGroupId = "myfriends"; await faceServiceClient.CreatePersonGroupAsync(personGroupId, "MyFriends"); // Define WongChiMan CreatePersonResult friend1 = await faceServiceClient.CreatePersonAsync( // Id of the person group that the person belonged to personGroupId, // Name of the person "Wong Chi Man" ); // Define WongSumWai and TsangChiWai in the same way // Define Wong Sum Wing CreatePersonResult friend2 = await faceServiceClient.CreatePersonAsync( // Id of the person group that the person belonged to personGroupId, // Name of the person "Wong Sum Wing" ); // Define TsangChiWai CreatePersonResult friend3 = await faceServiceClient.CreatePersonAsync( // Id of the person group that the person belonged to personGroupId, // Name of the person "Tsang Chi Wai" ); // Define Robin CreatePersonResult friend4 = await faceServiceClient.CreatePersonAsync( // Id of the person group that the person belonged to personGroupId, // Name of the person "Robin" ); myoutputBox.Text += " There are 4 friends I know: \n"; // Directory contains image files of WongChiMan const string friend1ImageDir = @"C:\TestPhotos\SingleImage\WongChiMan\"; 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); } } myoutputBox.Text += " Wong Chi Man, "; // Do the same for WongSumWai and TsangChiWai // Directory contains image files of Anna const string friend2ImageDir = @"C:\TestPhotos\SingleImage\WongSumWai\"; foreach (string imagePath in Directory.GetFiles(friend2ImageDir, "*.jpg")) { using (Stream s = File.OpenRead(imagePath)) { // Detect faces in the image and add to WongSumWai await faceServiceClient.AddPersonFaceAsync( personGroupId, friend2.PersonId, s); } } myoutputBox.Text += " Wong Sum Wing, "; // Directory contains image files of Anna const string friend3ImageDir = @"C:\TestPhotos\SingleImage\TsangChiWai\"; foreach (string imagePath in Directory.GetFiles(friend3ImageDir, "*.jpg")) { using (Stream s = File.OpenRead(imagePath)) { // Detect faces in the image and add to TsangChiWai await faceServiceClient.AddPersonFaceAsync( personGroupId, friend3.PersonId, s); } } myoutputBox.Text += " Tsang Chi Wai, "; // Directory contains image files of Anna const string friend4ImageDir = @"C:\TestPhotos\SingleImage\Robin\"; foreach (string imagePath in Directory.GetFiles(friend4ImageDir, "*.jpg")) { using (Stream s = File.OpenRead(imagePath)) { // Detect faces in the image and add to Robin await faceServiceClient.AddPersonFaceAsync( personGroupId, friend4.PersonId, s); } } myoutputBox.Text += " Robin \n"; // Train the group myoutputBox.Text += " \n \n * A Moment Please ...Training the group in progress ............... "; await faceServiceClient.TrainPersonGroupAsync(personGroupId); System.Threading.Thread.Sleep(10000); myoutputBox.Text += " * Success : Training the group ............... \n \n"; myoutputBox.Text += "* Please Click the button *Upload Photo* or *Take a Photo* To Authenticate you \n"; myoutputBox.Text += "\n * ============================================================ \n"; BrowseButton1.IsEnabled = false; BrowseButton2.IsEnabled = true; TakePhotoButton.IsEnabled = true; } // --------- End Robin Added for the BrowseButton_Click1 ------------------
/// <summary> /// Create a new Person in the Person Group of the Face Resource /// </summary> /// <param name="sender">A sender object</param> /// <param name="e">RoutedEventArgs</param> /// <remarks> /// <para>Person can't already exist in the Person Group</para> /// </remarks> private async void CreatePersonButton_ClickAsync(object sender, RoutedEventArgs e) { //Clear Globals personName = PersonNameTextBox.Text; //Reset UI Globals JSONTextBlock.Text = ""; JSONHeaderTextBlock.Text = ""; InfoHeaderTextBlock.Text = ""; UpdateUserDataPayloadTextBlock.Text = ""; UpdateUserDataStatusTextBlock.Text = ""; SubmissionStatusTextBlock.Text = ""; TrainStatusTextBlock.Text = ""; //Reset UI Colors UpdateUserDataStatusTextBlock.Foreground = new SolidColorBrush(Colors.Black); SubmissionStatusTextBlock.Foreground = new SolidColorBrush(Colors.Black); TrainStatusTextBlock.Foreground = new SolidColorBrush(Colors.Black); PersonStatusTextBlock.Foreground = new SolidColorBrush(Colors.Black); //Logic if (knownGroup != null && personName.Length > 0) { CreatePersonErrorText.Visibility = Visibility.Collapsed; //Check if this person already exist bool personAlreadyExist = false; Person[] ppl = await GetKnownPeople(); foreach (Person p in ppl) { if (p.Name == personName) { personAlreadyExist = true; PersonStatusTextBlock.Text = $"Person already exist: {p.Name} ID: {p.PersonId}"; PersonStatusTextBlock.Foreground = new SolidColorBrush(Colors.Red); } } if (!personAlreadyExist) { await ApiCallAllowed(true); CreatePersonResult result = await faceServiceClient.CreatePersonAsync(personGroupId, personName); if (null != result && null != result.PersonId) { personId = result.PersonId; PersonStatusTextBlock.Text = "Created new person: " + result.PersonId; PersonStatusTextBlock.Foreground = new SolidColorBrush(Colors.Green); } FetchPersonButton_ClickAsync(this, new RoutedEventArgs()); } } else { CreatePersonErrorText.Text = "Please provide a name above, and ensure that the above person group section has been completed."; CreatePersonErrorText.Visibility = Visibility.Visible; } }
// Function for Creating Group and Training the data // Run required only one time private async void CreatePersonGroup() { // Create an empty person group string personGroupId = "myfriends"; await faceServiceClient.CreatePersonGroupAsync(personGroupId, "MyFriends"); // Define Manas CreatePersonResult friend1 = await faceServiceClient.CreatePersonAsync( // Id of the person group that the person belonged to personGroupId, // Name of the person "Manas" ); // Define Ameya CreatePersonResult friend2 = await faceServiceClient.CreatePersonAsync( // Id of the person group that the person belonged to personGroupId, // Name of the person "Ameya" ); // Define Shubhankar CreatePersonResult friend3 = await faceServiceClient.CreatePersonAsync( // Id of the person group that the person belonged to personGroupId, // Name of the person "Shubhankar" ); // Directory contains image files of Manas const string friend1ImageDir = @"D:\Pictures\MyFriends\Manas\"; foreach (string imagePath in Directory.GetFiles(friend1ImageDir, "*.jpg")) { TitleText.Text = imagePath; using (Stream s = File.OpenRead(imagePath)) { // Detect faces in the image and add to Anna await faceServiceClient.AddPersonFaceAsync( personGroupId, friend1.PersonId, s); } } // Directory contains image files of Ameya const string friend2ImageDir = @"D:\Pictures\MyFriends\Ameya\"; foreach (string imagePath in Directory.GetFiles(friend2ImageDir, "*.jpg")) { using (Stream s = File.OpenRead(imagePath)) { // Detect faces in the image and add to Anna await faceServiceClient.AddPersonFaceAsync( personGroupId, friend2.PersonId, s); } } // Directory contains image files of Manas const string friend3ImageDir = @"D:\Pictures\MyFriends\Shubhankar\"; foreach (string imagePath in Directory.GetFiles(friend3ImageDir, "*.jpg")) { using (Stream s = File.OpenRead(imagePath)) { // Detect faces in the image and add to Anna await faceServiceClient.AddPersonFaceAsync( personGroupId, friend3.PersonId, s); } } TitleText.Text = "Train about to start"; await faceServiceClient.TrainPersonGroupAsync(personGroupId); TitleText.Text = "Train started"; TrainingStatus trainingStatus = null; while (true) { trainingStatus = await faceServiceClient.GetPersonGroupTrainingStatusAsync(personGroupId); int count = 0; if (trainingStatus.Status.ToString() != "running") { break; } else { count++; } TitleText.Text = count.ToString(); await Task.Delay(1000); } TitleText.Text = "Finished"; }
public async Task <string> CreatePersonAsync(string personGroupId, string name) { CreatePersonResult res = await faceClient.CreatePersonAsync(personGroupId, name); return(res.PersonId.ToString()); }
public async void FindByGroupPerson() { string personGroupId = "formatura"; var ExistsPersonGroup = FaceServiceHelper.GetPersonGroupsAsync(personGroupId).Result.PersonGroupId == personGroupId; if (!ExistsPersonGroup) { await FaceServiceHelper.CreatePersonGroupAsync(personGroupId, "Minha formatura"); } CreatePersonResult ana = await FaceServiceHelper.CreatePersonAsync(personGroupId, "Ana"); const string friend1ImageDir = @"M:\Onedrive\Projetos\Detector Face beta\ana"; foreach (string imagePath in Directory.GetFiles(friend1ImageDir, "*.jpg")) { using (Stream s = File.OpenRead(imagePath)) { try { await FaceServiceHelper.AddPersonFaceAsync(personGroupId, ana.PersonId, s); } catch (Exception ex) { continue; } } } await FaceServiceHelper.TrainPersonGroupAsync(personGroupId); TrainingStatus trainingStatus = null; while (true) { trainingStatus = await FaceServiceHelper.GetPersonGroupTrainingStatusAsync(personGroupId); if (trainingStatus.Status != Status.Running) { break; } await Task.Delay(1000); } string template = @"C:\Users\clebe\Desktop\template2.jpg"; using (Stream s = File.OpenRead(template)) { var faces = await FaceServiceHelper.DetectAsync(s); var faceIds = faces.Select(face => face.FaceId).ToArray(); var results = await FaceServiceHelper.IdentifyAsync(personGroupId, faceIds); foreach (var identifyResult in results) { Console.WriteLine("Result of face: {0}", identifyResult.FaceId); if (identifyResult.Candidates.Length == 0) { Console.WriteLine("No one identified"); } else { var candidateId = identifyResult.Candidates[0].PersonId; var person = await FaceServiceHelper.GetPersonAsync(personGroupId, candidateId); Console.WriteLine("Identified as {0}", person.Name); } } Console.ReadKey(); } }
//Compare client faces private async void DefineClientGroup(string filePath) { // Create an empty person group string personGroupId = "clients"; try { await face_service_client.CreatePersonGroupAsync(personGroupId, "Clients"); } catch (Exception) { } // Define Andr CreatePersonResult client2 = await face_service_client.CreatePersonAsync(personGroupId, "Mashulya"); // Directory contains image files of Andr const string client2ImageDir = @"C:\Users\Kirill\Desktop\Mashulya\"; foreach (string imagePath in Directory.GetFiles(client2ImageDir, "*.jpg")) { using (Stream s = File.OpenRead(imagePath)) { // Detect faces in the image and add to Andr await face_service_client.AddPersonFaceAsync( personGroupId, client2.PersonId, s); } } await face_service_client.TrainPersonGroupAsync(personGroupId); TrainingStatus trainingStatus = null; while (true) { trainingStatus = await face_service_client.GetPersonGroupTrainingStatusAsync(personGroupId); if (trainingStatus.Status != Status.Running) { break; } await Task.Delay(1000); } using (Stream s = File.OpenRead(filePath)) { var faces = await face_service_client.DetectAsync(s); var faceIds = faces.Select(face => face.FaceId).ToArray(); var results = await face_service_client.IdentifyAsync(personGroupId, faceIds); foreach (var identifyResult in results) { Console.WriteLine("Result of face: {0}", identifyResult.FaceId); if (identifyResult.Candidates.Length == 0) { MessageBox.Show("No one identified"); } else { // Get top 1 among all candidates returned var candidateId = identifyResult.Candidates[0].PersonId; var person = await face_service_client.GetPersonAsync(personGroupId, candidateId); MessageBox.Show("Identified as " + person.Name); } } } }
public async void trainmodel() { try { // Create an empty person group string personGroupId = "myfriends"; using (FaceServiceClient faceClient = new FaceServiceClient(faceapikey)) { //await faceClient.CreatePersonGroupAsync(personGroupId, "myfriends"); // Define name here CreatePersonResult friend1 = await faceClient.CreatePersonAsync( // Id of the person group that the person belonged to personGroupId, // Name of the person name.Text.ToString() ); // Define Bill and Clare in the same way // Directory contains image files of Anna //const string friend1ImageDir = Server.MapPath("~/images/People/" + name.Text.ToString() + "/"); //foreach (string imagePath in Directory.GetFiles(Server.MapPath("~/images/People/" + name.Text.ToString() + "/"), "*.jpg")) //{ // using (Stream s = File.OpenRead(imagePath)) // { // // Detect faces in the image and add to Anna // await faceClient.AddPersonFaceAsync( // personGroupId, friend1.PersonId, s); // } //} // Retrieve storage account from connection string. CloudStorageAccount storageAccount = CloudStorageAccount.Parse( CloudConfigurationManager.GetSetting("StorageConnectionString")); // Create the blob client. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Retrieve reference to a previously created container. CloudBlobContainer container = blobClient.GetContainerReference("bbpeople"); // Loop over items within the container and output the length and URI. foreach (IListBlobItem item in container.ListBlobs(null, false)) { if (item.GetType() == typeof(CloudBlockBlob)) { CloudBlockBlob blob = (CloudBlockBlob)item; if (blob.Name.StartsWith(name.Text)) { CloudBlockBlob blockBlob2 = container.GetBlockBlobReference(blob.Name); string text; using (var memoryStream = new MemoryStream()) { //memoryStream.Position = 0; blockBlob2.DownloadToStream(memoryStream); //text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray(),0,(int)memoryStream.Length); //var mem = new MemoryStream(); //memoryStream.Position = 0; //memoryStream.CopyTo(mem, (int)memoryStream.Length); //MemoryStream mStrm = new MemoryStream(Encoding.UTF8.GetBytes(text)); //text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray()); // Detect faces in the image and add to Anna //await faceClient.AddPersonFaceAsync(personGroupId, friend1.PersonId, memoryStream); //await faceClient.AddPersonFaceAsync(personGroupId, friend1.PersonId, blob.Name); try { await faceClient.AddPersonFaceAsync(personGroupId, friend1.PersonId, blob.Uri.ToString()); } catch (Exception e) { showerror(e); //throw e; } } } //Console.WriteLine("Block blob of length {0}: {1}", blob.Properties.Length, blob.Uri); } else if (item.GetType() == typeof(CloudPageBlob)) { CloudPageBlob pageBlob = (CloudPageBlob)item; //Console.WriteLine("Page blob of length {0}: {1}", pageBlob.Properties.Length, pageBlob.Uri); } else if (item.GetType() == typeof(CloudBlobDirectory)) { CloudBlobDirectory directory = (CloudBlobDirectory)item; //Console.WriteLine("Directory: {0}", directory.Uri); } } // Do the same for Other Users as well and Clare await faceClient.TrainPersonGroupAsync(personGroupId); TrainingStatus trainingStatus = null; while (true) { trainingStatus = await faceClient.GetPersonGroupTrainingStatusAsync(personGroupId); if (trainingStatus.Status.ToString() != "running") { break; } await Task.Delay(1000); } } } catch (Exception ex) { showerror(ex); //throw ex; } }
static async void train() { FaceServiceClient faceServiceClient = new FaceServiceClient("XXXXXXXXXXXXXXXX"); // Create an empty person group string personGroupId = "test1"; await faceServiceClient.CreatePersonGroupAsync(personGroupId, "Test 1"); CreatePersonResult friend1 = await faceServiceClient.CreatePersonAsync(personGroupId, "Anna"); CreatePersonResult friend2 = await faceServiceClient.CreatePersonAsync(personGroupId, "Bill"); CreatePersonResult friend3 = await faceServiceClient.CreatePersonAsync(personGroupId, "Clare"); // Directory contains image files of Anna const string friend1ImageDir = @"C:\Users\StanDotloe\OneDrive\Facial Recognition\Projects\Cognitive-Face-Windows-master\Data\PersonGroup\Family3-Lady"; const string friend2ImageDir = @"C:\Users\StanDotloe\OneDrive\Facial Recognition\Projects\Cognitive-Face-Windows-master\Data\PersonGroup\Family1-Dad"; const string friend3ImageDir = @"C:\Users\StanDotloe\OneDrive\Facial Recognition\Projects\Cognitive-Face-Windows-master\Data\PersonGroup\Family1-Mom"; 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); } } foreach (string imagePath in Directory.GetFiles(friend2ImageDir, "*.jpg")) { using (Stream s = File.OpenRead(imagePath)) { await faceServiceClient.AddPersonFaceAsync(personGroupId, friend2.PersonId, s); } } foreach (string imagePath in Directory.GetFiles(friend3ImageDir, "*.jpg")) { using (Stream s = File.OpenRead(imagePath)) { await faceServiceClient.AddPersonFaceAsync(personGroupId, friend3.PersonId, s); } } await faceServiceClient.TrainPersonGroupAsync(personGroupId); TrainingStatus trainingStatus = null; while (true) { trainingStatus = await faceServiceClient.GetPersonGroupTrainingStatusAsync(personGroupId); if (!(trainingStatus.Status.Equals("running"))) { break; } await Task.Delay(1000); } string testImageFile = @"C:\Users\StanDotloe\OneDrive\Facial Recognition\Projects\Cognitive-Face-Windows-master\Data\PersonGroup\Family3-Man\Family3-Man3.jpg"; 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) { Console.WriteLine("Result of face: {0}", identifyResult.FaceId); if (identifyResult.Candidates.Length == 0) { Console.WriteLine("No one identified"); } else { // Get top 1 among all candidates returned var candidateId = identifyResult.Candidates[0].PersonId; var person = await faceServiceClient.GetPersonAsync(personGroupId, candidateId); Console.WriteLine("Identified as {0}", person.Name); } } } }
private async void detectRegisterFace(CreatePersonResult friend1, CreatePersonResult friend2, CreatePersonResult friend3) { const string friend1ImageDir = @"<Directory with images of Person 1>"; foreach (string imagePath in Directory.GetFiles(friend1ImageDir, "*.jpg")) { using (Stream s = File.OpenRead(imagePath)) { // Detect faces in the image and add them. try { await faceServiceClient.AddPersonFaceAsync( "myfriends", friend1.PersonId, s); }catch (Exception e) { Console.WriteLine(e.Message); } } } const string friend2ImageDir = @"<Directory with images of Person 2>"; foreach (string imagePath in Directory.GetFiles(friend2ImageDir, "*.jpg")) { using (Stream s = File.OpenRead(imagePath)) { // Detect faces in the image and add them. await faceServiceClient.AddPersonFaceAsync( "myfriends", friend2.PersonId, s); } } const string friend3ImageDir = @"<Directory with images of Person 3>"; foreach (string imagePath in Directory.GetFiles(friend3ImageDir, "*.jpg")) { using (Stream s = File.OpenRead(imagePath)) { // Detect faces in the image and add. await faceServiceClient.AddPersonFaceAsync( "myfriends", friend3.PersonId, s); } } }
public async System.Threading.Tasks.Task <IHttpActionResult> POSTAsync() { FaceServiceClient faceSC = new FaceServiceClient("9ed1e677b9bd402c83697c7c9e31e3e7", "https://eastasia.api.cognitive.microsoft.com/face/v1.0"); string ChannelAccessToken = Properties.Settings.Default.ChannelAccessToken; string groupID = "group1"; string replyToken = ""; //回覆訊息 string Message = "無法辨識的指令,請使用功能選項輸入關鍵字!"; try { //剖析JSON string postData = Request.Content.ReadAsStringAsync().Result; var ReceivedMessage = isRock.LineBot.Utility.Parsing(postData); replyToken = ReceivedMessage.events[0].replyToken; using (SqlConnection cnn1 = new SqlConnection(sqlcn)) { using (SqlCommand cmd1 = new SqlCommand()) { cmd1.Connection = cnn1; cmd1.CommandText = "SELECT A.memType, A.adminID, A.studentID, B.personID FROM dbo.members AS A, dbo.students AS B WHERE A.userID = @userId AND A.studentID = B.studentID"; cmd1.Parameters.Add("@userId", SqlDbType.NVarChar).Value = ReceivedMessage.events[0].source.userId; cnn1.Open(); SqlDataReader rr = cmd1.ExecuteReader(); IDExist = rr.HasRows; if (IDExist) { rr.Read(); memType = int.Parse(rr[0].ToString()); adminID = int.Parse(rr[1].ToString()); studentID = int.Parse(rr[2].ToString()); personID = rr[3].ToString(); } rr.Close(); cmd1.Dispose(); cnn1.Close(); } } using (SqlConnection cnn11 = new SqlConnection(sqlcn)) { using (SqlCommand cmd11 = new SqlCommand()) { cmd11.Connection = cnn11; cmd11.CommandText = "SELECT * FROM dbo.classes"; cnn11.Open(); SqlDataReader rr = cmd11.ExecuteReader(); if (rr.HasRows) { while (rr.Read()) { TimeSpan timeSpan = DateTime.Now.Subtract(DateTime.Parse(rr[1].ToString())); if (DateTime.Parse(rr[1].ToString()).ToShortDateString() == DateTime.Now.ToShortDateString()) { nowD = int.Parse(rr[0].ToString()); } else if (timeSpan.TotalDays > 0) { prevD = int.Parse(rr[0].ToString()); prevDT = DateTime.Parse(rr[1].ToString()).ToShortDateString(); } else { nextD = int.Parse(rr[0].ToString()); nextDT = DateTime.Parse(rr[1].ToString()).ToShortDateString(); break; } } } rr.Close(); cmd11.Dispose(); cnn11.Close(); } } //判斷初次加入好友 if (ReceivedMessage.events.FirstOrDefault().type == "follow") { if (!IDExist) { using (SqlConnection cnn2 = new SqlConnection(sqlcn)) { using (SqlCommand cmd2 = new SqlCommand()) { cmd2.Connection = cnn2; cmd2.CommandText = "INSERT INTO dbo.members(userID, memType) VALUES(@userId, 0)"; cmd2.Parameters.Add("@userId", SqlDbType.NVarChar).Value = ReceivedMessage.events[0].source.userId; cnn2.Open(); if (cmd2.ExecuteNonQuery() == 1) { Message = "登錄LineBot帳號成功!\n請輸入您的ID(學生輸入學號 如:1091234,老師輸入註冊代碼):"; } else { Message = "登錄LineBot帳號失敗!\n請刪除此LineBot後重新加入或找教授/助教確認個人資料。"; } cmd2.Dispose(); cnn2.Close(); } } } else { Message = "您的userID已被註冊過!\n請隨意傳送資料或找教授/助教確認個人資料。"; } isRock.LineBot.Utility.ReplyMessage(replyToken, Message, ChannelAccessToken); return(Ok()); } else if (ReceivedMessage.events.FirstOrDefault().type == "message") { if (ReceivedMessage.events.FirstOrDefault().message.type.Trim().ToLower() == "text") { if (memType == 0) { if (ReceivedMessage.events[0].message.text.Length != 7) { Message = "輸入的ID字數錯誤,ID為7個字的字串!"; } else { using (SqlConnection cnn3 = new SqlConnection(sqlcn)) { using (SqlCommand cmd3 = new SqlCommand()) { cmd3.Connection = cnn3; cmd3.CommandText = "SELECT studentID FROM dbo.students WHERE studentAct = @studentAct"; cmd3.Parameters.Add("@studentAct", SqlDbType.NVarChar).Value = ReceivedMessage.events[0].message.text; cnn3.Open(); SqlDataReader rr = cmd3.ExecuteReader(); if (rr.HasRows) { memType = 2; rr.Read(); studentID = int.Parse(rr[0].ToString()); } rr.Close(); cmd3.Dispose(); cnn3.Close(); } } if (memType == 0) { using (SqlConnection cnn3 = new SqlConnection(sqlcn)) { using (SqlCommand cmd3 = new SqlCommand()) { cmd3.Connection = cnn3; cmd3.CommandText = "SELECT adminID FROM dbo.admins WHERE adminAct = @adminAct"; cmd3.Parameters.Add("@adminAct", SqlDbType.NVarChar).Value = ReceivedMessage.events[0].message.text; cnn3.Open(); SqlDataReader rr = cmd3.ExecuteReader(); if (rr.HasRows) { memType = 1; rr.Read(); adminID = int.Parse(rr[0].ToString()); } rr.Close(); cmd3.Dispose(); cnn3.Close(); } } } if (memType > 0) { if (memType == 1) { using (SqlConnection cnn4 = new SqlConnection(sqlcn)) { using (SqlCommand cmd4 = new SqlCommand()) { cmd4.Connection = cnn4; CreatePersonResult pr = await faceSC.CreatePersonAsync(groupID, studentID.ToString()); cmd4.CommandText = "UPDATE dbo.admins SET adminExist = 1 WHERE adminID = @adminID"; cmd4.Parameters.Add("@adminID", SqlDbType.Int).Value = adminID; cnn4.Open(); cmd4.ExecuteNonQuery(); cmd4.Dispose(); cnn4.Close(); } } } else if (memType == 2) { using (SqlConnection cnn4 = new SqlConnection(sqlcn)) { using (SqlCommand cmd4 = new SqlCommand()) { cmd4.Connection = cnn4; CreatePersonResult pr = await faceSC.CreatePersonAsync(groupID, studentID.ToString()); cmd4.CommandText = "UPDATE dbo.students SET personID = @personID, studentExist = 1 WHERE studentID = @studentID"; cmd4.Parameters.Add("@personID", SqlDbType.NVarChar).Value = pr.PersonId.ToString(); cmd4.Parameters.Add("@studentID", SqlDbType.Int).Value = studentID; cnn4.Open(); cmd4.ExecuteNonQuery(); cmd4.Dispose(); cnn4.Close(); } } } using (SqlConnection cnn4 = new SqlConnection(sqlcn)) { using (SqlCommand cmd4 = new SqlCommand()) { cmd4.Connection = cnn4; cmd4.CommandText = "UPDATE dbo.members SET adminID = @adminID, studentID = @studentID, memType = @memType WHERE userID = @userId"; cmd4.Parameters.Add("@adminID", SqlDbType.Int).Value = adminID; cmd4.Parameters.Add("@studentID", SqlDbType.Int).Value = studentID; cmd4.Parameters.Add("@memType", SqlDbType.Int).Value = memType; cmd4.Parameters.Add("@userId", SqlDbType.NVarChar).Value = ReceivedMessage.events[0].source.userId; cnn4.Open(); if (cmd4.ExecuteNonQuery() == 1) { if (memType == 1) { Message = "個人資訊註冊完畢\n感謝您的填寫\n\n您可以開始傳送照片點名及使用功能選項中的查詢點名結果確認出席狀況"; } else if (memType == 2) { Message = "請傳送臉部可清晰辨識五官的個人照(還需三張):"; } } else { Message = "登入ID失敗!\n請重新輸入或找教授/助教確認個人資料。"; } cmd4.Dispose(); cnn4.Close(); } } } } } else if (ReceivedMessage.events[0].message.text == "[線上請假]") { if (nextD == -1) { Message = "本課程已經結束!"; isRock.LineBot.Utility.ReplyMessage(replyToken, Message, ChannelAccessToken); return(Ok()); } if (memType == 5) { using (SqlConnection cnn10 = new SqlConnection(sqlcn)) { using (SqlCommand cmd10 = new SqlCommand()) { cmd10.Connection = cnn10; cmd10.CommandText = "INSERT INTO dbo. rollCall(studentID, classID, RCState, picID, RCTime) VALUES(@studentID, @classID, 2, 1, @RCTime)"; cmd10.Parameters.Add("@studentID", SqlDbType.Int).Value = studentID; cmd10.Parameters.Add("@classID", SqlDbType.Int).Value = nextD; cmd10.Parameters.Add("@RCTime", SqlDbType.DateTime).Value = DateTime.Now; cnn10.Open(); if (cmd10.ExecuteNonQuery() != 1) { Message = "請假失敗!\n請重新傳送或找教授/助教確認個人資料。"; } else { Message = "下一堂課時間為 " + nextDT + "\n\n已請假成功!"; } cmd10.Dispose(); cnn10.Close(); } } } else if (memType == 1) { using (SqlConnection cnn8 = new SqlConnection(sqlcn)) { using (SqlCommand cmd8 = new SqlCommand()) { cmd8.Connection = cnn8; cmd8.CommandText = "SELECT DISTINCT A.studentAct FROM dbo.students AS A, dbo.rollCall AS B WHERE A.studentID = B.studentID AND B.RCState = 2 AND B.classID = @classID"; cmd8.Parameters.Add("@classID", SqlDbType.Int).Value = nextD; cnn8.Open(); SqlDataReader rr = cmd8.ExecuteReader(); if (!rr.HasRows) { Message = "下一堂課時間為 " + nextDT + "\n\n今天無人請假!"; } else { Message = "下一堂課時間為 " + nextDT + "\n\n請假學生:"; while (rr.Read()) { Message += "\n" + rr[0].ToString(); } } rr.Close(); cmd8.Dispose(); cnn8.Close(); } } } } else if (ReceivedMessage.events[0].message.text == "[查詢點名結果]") { if (prevD == -1 && nowD == -1) { Message = "本課程還沒開始!"; isRock.LineBot.Utility.ReplyMessage(replyToken, Message, ChannelAccessToken); return(Ok()); } if (memType == 5) { string temp = ""; using (SqlConnection cnn12 = new SqlConnection(sqlcn)) { using (SqlCommand cmd12 = new SqlCommand()) { cmd12.Connection = cnn12; cmd12.CommandText = "SELECT RCState, RCTime FROM dbo.rollCall WHERE studentID = @studentID AND classID = @classID ORDER BY RCID DESC"; cmd12.Parameters.Add("@studentID", SqlDbType.Int).Value = studentID; if (nowD == -1) { cmd12.Parameters.Add("@classID", SqlDbType.Int).Value = prevD; Message = "最近一次點名紀錄為\n" + prevDT; } else { cmd12.Parameters.Add("@classID", SqlDbType.Int).Value = nowD; Message = "最近一次點名紀錄為\n" + DateTime.Now.ToShortDateString(); } cnn12.Open(); SqlDataReader rr = cmd12.ExecuteReader(); if (!rr.HasRows) { temp = "缺席"; } else { rr.Read(); Message += " " + DateTime.Parse(rr[1].ToString()).ToShortTimeString(); if (rr[0].ToString() == "2") { temp = "請假"; } else if (rr[0].ToString() == "1") { temp = "出席"; } else { temp = "缺席"; } } Message += "\n\n您的點名紀錄為: " + temp; rr.Close(); cmd12.Dispose(); cnn12.Close(); } } } else if (memType == 1) { using (SqlConnection cnn8 = new SqlConnection(sqlcn)) { using (SqlCommand cmd8 = new SqlCommand()) { cmd8.Connection = cnn8; cmd8.CommandText = "SELECT DISTINCT A.studentAct, B.RCState FROM (SELECT * FROM dbo.students WHERE studentID > 1) AS A LEFT OUTER JOIN dbo.rollCall AS B ON A.studentID = B.studentID AND B.classID = @classID ORDER BY B.RCState DESC"; if (nowD == -1) { cmd8.Parameters.Add("@classID", SqlDbType.Int).Value = prevD; Message = "最近一次點名紀錄為\n" + prevDT; } else { cmd8.Parameters.Add("@classID", SqlDbType.Int).Value = nowD; Message = "最近一次點名紀錄為\n" + DateTime.Now.ToShortDateString(); } cnn8.Open(); SqlDataReader rr = cmd8.ExecuteReader(); bool check = true; Message += "\n\n請假:"; check = rr.Read(); while (check && rr[1].ToString() == "2") { Message += "\n" + rr[0].ToString(); check = rr.Read(); } Message += "\n\n出席:"; while (check && rr[1].ToString() == "1") { Message += "\n" + rr[0].ToString(); check = rr.Read(); } Message += "\n\n缺席:"; while (check) { Message += "\n" + rr[0].ToString(); check = rr.Read(); } rr.Close(); cmd8.Dispose(); cnn8.Close(); } } } } else if (ReceivedMessage.events[0].message.text == "[使用說明]") { Message = "●查詢點名結果:\n" + "學生可以看到自己最近一次上課出席狀況\n" + "老師可以看到最近一堂課學生出缺勤狀況\n\n" + "●線上請假:\n" + "學生可以為下一次的課程請假\n" + "老師可以看到下一次上課請假學生資訊\n\n" + "●管理網頁:\n" + "此功能學生不適用\n" + "老師點選可直接連結到點名後台,手動更改點名資訊\n\n" + "●智慧點名方式:\n" + "此功能學生不適用\n" + "老師拍攝並傳送教室學生照片,系統會透過人臉辨識完成點名"; } /*else if (ReceivedMessage.events[0].message.text == "[管理網站]") * { * Message = "http://140.138.155.175:8080/index.aspx"; * }*/ isRock.LineBot.Utility.ReplyMessage(replyToken, Message, ChannelAccessToken); return(Ok()); } else if (ReceivedMessage.events.FirstOrDefault().message.type.Trim().ToLower() == "image") { if (memType >= 1 && memType <= 4) { //取得contentid var LineContentID = ReceivedMessage.events.FirstOrDefault().message.id.ToString(); //取得bytedata var filebody = isRock.LineBot.Utility.GetUserUploadedContent(LineContentID, ChannelAccessToken); var ms = new MemoryStream(filebody); Face[] faces = await faceSC.DetectAsync(ms); string picPath = "/Temp/" + Guid.NewGuid() + ".jpg"; var path = System.Web.HttpContext.Current.Request.MapPath(picPath); //上傳圖片 File.WriteAllBytes(path, filebody); using (SqlConnection cnn15 = new SqlConnection(sqlcn)) { using (SqlCommand cmd15 = new SqlCommand()) { cmd15.Connection = cnn15; cmd15.CommandText = "INSERT INTO dbo.pictures(studentID, picPath, picTime) VALUES(@studentID, @picPath, @picTime)"; cmd15.Parameters.Add("@studentID", SqlDbType.Int).Value = studentID; cmd15.Parameters.Add("@picPath", SqlDbType.VarChar).Value = picPath; cmd15.Parameters.Add("@picTime", SqlDbType.DateTime).Value = DateTime.Now; cnn15.Open(); cmd15.ExecuteNonQuery(); cmd15.Dispose(); cnn15.Close(); } } if (memType != 1) { if (faces.Length != 1) { Message = "無法辨識,請重新傳送五官清晰的個人照!"; isRock.LineBot.Utility.ReplyMessage(replyToken, Message, ChannelAccessToken); return(Ok()); } //上傳圖片 memType++; using (SqlConnection cnn7 = new SqlConnection(sqlcn)) { using (SqlCommand cmd7 = new SqlCommand()) { cmd7.Connection = cnn7; cmd7.CommandText = "UPDATE dbo.members SET memType = @memType WHERE studentID = @studentID"; cmd7.Parameters.Add("@memType", SqlDbType.Int).Value = memType; cmd7.Parameters.Add("@studentID", SqlDbType.Int).Value = studentID; cnn7.Open(); if (cmd7.ExecuteNonQuery() != 1) { Message = "登入圖片失敗!\n請重新傳送或找教授/助教確認個人資料。"; } cmd7.Dispose(); cnn7.Close(); } } MemoryStream stream = new MemoryStream(filebody); AddPersistedFaceResult result = await faceSC.AddPersonFaceAsync(groupID, Guid.Parse(personID), stream); await faceSC.TrainPersonGroupAsync(groupID); if (memType == 3) { Message = "請傳送臉部可清晰辨識五官的個人照(還需兩張):"; } else if (memType == 4) { Message = "請傳送臉部可清晰辨識五官的個人照(還需一張):"; } else if (memType == 5) { Message = "個人資訊註冊完畢\n感謝您的填寫\n\n您可以開始使用功能選項中的查詢點名功能及線上請假功能"; } } else { if (nowD == -1) { Message = "今日沒有上課喔!"; isRock.LineBot.Utility.ReplyMessage(replyToken, Message, ChannelAccessToken); return(Ok()); } using (SqlConnection cnn16 = new SqlConnection(sqlcn)) { using (SqlCommand cmd16 = new SqlCommand()) { cmd16.Connection = cnn16; cmd16.CommandText = "SELECT picID FROM dbo.pictures WHERE picPath = @picPath"; cmd16.Parameters.Add("@picPath", SqlDbType.NVarChar).Value = picPath; cnn16.Open(); SqlDataReader rr = cmd16.ExecuteReader(); if (rr.HasRows) { rr.Read(); picID = int.Parse(rr[0].ToString()); } cmd16.Dispose(); cnn16.Close(); } } // 將照片中的臉,與指定的PersonGroup進行比對 if (faces != null) { Message = "已偵測到 " + faces.Length + " 人\n"; // 將這張照片回傳的人臉,取出每一張臉的FaceId並進行轉換成Guid Guid[] faceGuids = faces.Select(x => x.FaceId).ToArray(); int pCount = 0; if (faceGuids.Length > 0) { // 透過Identify,找出在這張照片中,所有辨識出的人臉,是否有包含在PersonGroup中的所有人員 IdentifyResult[] result = await faceSC.IdentifyAsync(groupID, faceGuids); // 取得照片中在PersonGroup裡的人 for (int i = 0; i < result.Length; i++) { for (int p = 0; p < result[i].Candidates.Length; p++) { Person person = await faceSC.GetPersonAsync(groupID, result[i].Candidates[p].PersonId); string strPersonId = person.Name; pCount++; using (SqlConnection cnn9 = new SqlConnection(sqlcn)) { using (SqlCommand cmd9 = new SqlCommand()) { cmd9.Connection = cnn9; cmd9.CommandText = "INSERT INTO dbo. rollCall(studentID, classID, RCState, picID, RCTime) VALUES(@studentID, @classID, 1, @picID, @RCTime)"; cmd9.Parameters.Add("@studentID", SqlDbType.Int).Value = int.Parse(strPersonId); cmd9.Parameters.Add("@classID", SqlDbType.Int).Value = nowD; cmd9.Parameters.Add("@picID", SqlDbType.Int).Value = picID; cmd9.Parameters.Add("@RCTime", SqlDbType.DateTime).Value = System.DateTime.Now; cnn9.Open(); if (cmd9.ExecuteNonQuery() != 1) { Message = "點名失敗,請再嘗試一次!"; } cmd9.Dispose(); cnn9.Close(); } } } } Message += "成功辨識 " + pCount + " 人"; } } } //ReplyMessage isRock.LineBot.Utility.ReplyMessage(replyToken, Message, ChannelAccessToken); return(Ok()); } else { isRock.LineBot.Utility.ReplyMessage(replyToken, "else", ChannelAccessToken); return(Ok()); } } } } catch (Exception ex) { isRock.LineBot.Utility.ReplyMessage(replyToken, "錯誤訊息: " + ex.Message + "\n請聯絡工程人員!", ChannelAccessToken); return(Ok()); } return(Ok()); }
public async Task <Tuple <string, CreatePersonResult> > AddNewPersonToGroup(string personGroupId, string personName) { CreatePersonResult person = await _faceServiceClient.CreatePersonAsync(personGroupId, personName); return(new Tuple <string, CreatePersonResult>(personGroupId, person)); }
static void Main(string[] args) { //Input oxfordKey Console.WriteLine("Please input the OxfordPrimaryKey: "); string oxfordProjectKey = Console.ReadLine(); FaceServiceClient faceClient = new FaceServiceClient(oxfordProjectKey); //Create PersonGroup string groupName = ""; string groupId = ""; Console.WriteLine("Create a new Person Group? [Y/N]"); string personGroupChoice = Console.ReadLine(); if (personGroupChoice == "Y") { Console.WriteLine("Please input the PersonGroup Name: "); groupName = Console.ReadLine(); groupId = Guid.NewGuid().ToString(); var runSync = Task.Factory.StartNew(new Func <Task>(async() => { await faceClient.CreatePersonGroupAsync(groupId, groupName); })).Unwrap(); runSync.Wait(); } else { Console.WriteLine("Please input the PersonGroup Id: "); groupId = Console.ReadLine(); } Console.WriteLine("Adding person and his photos......"); //Add Persons and Photos DirectoryInfo dirPrograms = new DirectoryInfo(Environment.CurrentDirectory); List <DirectoryInfo> dirs = new List <DirectoryInfo>(dirPrograms.EnumerateDirectories()); foreach (DirectoryInfo dirsplit in dirs) { string lastName = dirsplit.Name.Substring(dirsplit.Name.IndexOf("_") + 1, dirsplit.Name.Length - dirsplit.Name.IndexOf("_") - 1); string firstName = dirsplit.Name.Substring(0, dirsplit.Name.IndexOf("_")); //Create Person CreatePersonResult personResult = null; var runSync = Task.Factory.StartNew(new Func <Task>(async() => { personResult = await faceClient.CreatePersonAsync(groupId, firstName + " " + lastName); })).Unwrap(); runSync.Wait(); Console.WriteLine("Creating " + firstName + " " + lastName); //Add photos List <FileInfo> files = new List <FileInfo>(dirsplit.EnumerateFiles()); foreach (FileInfo filesplit in files) { FileStream fs0 = new FileStream(filesplit.Directory + "\\" + filesplit.Name, FileMode.Open); byte[] bytes = new byte[fs0.Length]; fs0.Read(bytes, 0, bytes.Length); fs0.Close(); Stream imageStream = new MemoryStream(bytes); AddPersistedFaceResult perFaceResult = null; runSync = Task.Factory.StartNew(new Func <Task>(async() => { perFaceResult = await faceClient.AddPersonFaceAsync(groupId, personResult.PersonId, imageStream); })).Unwrap(); runSync.Wait(); } } //Train and get training status faceClient.TrainPersonGroupAsync(groupId); TrainingStatus trStatus = null; do { Console.WriteLine("Waiting for training."); Thread.Sleep(3000); var runSync = Task.Factory.StartNew(new Func <Task>(async() => { trStatus = await faceClient.GetPersonGroupTrainingStatusAsync(groupId); })).Unwrap(); runSync.Wait(); } while (trStatus == null || trStatus.Status == Status.Running); Console.WriteLine("TrainingStatus: " + trStatus.Status.ToString()); //Write the info to txt file string data1 = "oxfordKey: " + oxfordProjectKey; string data2 = "PersonGroupId: " + groupId; StreamWriter sw = new StreamWriter("OxfordData.txt", false, Encoding.Default); sw.WriteLine(data1); sw.WriteLine(data2); sw.Close(); Console.ReadLine(); }
public async Task <AddPersistedFaceResult> RegisterPerson(string personGroupId, CreatePersonResult person, Stream stream) { var addPersistedFaceResult = await _faceServiceClient.AddPersonFaceAsync( personGroupId, person.PersonId, stream); return(addPersistedFaceResult); }
private async void Window_Loaded(object sender, RoutedEventArgs e) { // Create an empty person group // string personGroupId = "ncr13"; // await faceServiceClient.CreatePersonGroupAsync(personGroupId, ""); bool groupExists = false; try { //MainWindow.Log("Request: Group {0} will be used to build a person database. Checking whether the group exists.", GroupName); Title = String.Format("Request: Group {0} will be used to build a person database. Checking whether the group exists.", personGroupId); await faceServiceClient.GetPersonGroupAsync(personGroupId); groupExists = true; //MainWindow.Log("Response: Group {0} exists.", GroupName); Title = String.Format("Response: Group {0} exists.", personGroupId); } catch (FaceAPIException ex) { if (ex.ErrorCode != "PersonGroupNotFound") { //MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); Title = String.Format("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); return; } else { // MainWindow.Log("Response: Group {0} did not exist previously.", GroupName); Title = String.Format("Response: Group {0} did not exist previously.", personGroupId); } } if (groupExists) { var cleanGroup = System.Windows.MessageBox.Show(string.Format("Requires a clean up for group \"{0}\" before setting up a new person database. Click OK to proceed, group \"{0}\" will be cleared.", personGroupId), "Warning", MessageBoxButton.OKCancel); if (cleanGroup == MessageBoxResult.OK) { await faceServiceClient.DeletePersonGroupAsync(personGroupId); } else { return; } } //MainWindow.Log("Request: Creating group \"{0}\"", GroupName); Title = String.Format("Request: Creating group \"{0}\"", personGroupId); try { await faceServiceClient.CreatePersonGroupAsync(personGroupId, personGroupId); // MainWindow.Log("Response: Success. Group \"{0}\" created", personGroupId); Title = String.Format("Response: Success. Group \"{0}\" created", personGroupId); } catch (FaceAPIException ex) { //MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); Title = String.Format("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); return; } // Define Anna CreatePersonResult friend1 = await faceServiceClient.CreatePersonAsync( // Id of the person group that the person belonged to personGroupId, // Name of the person "Anna" ); // Define Toshif CreatePersonResult friend2 = await faceServiceClient.CreatePersonAsync( // Id of the person group that the person belonged to personGroupId, // Name of the person "Toshif" ); // Define Clare CreatePersonResult friend3 = await faceServiceClient.CreatePersonAsync( // Id of the person group that the person belonged to personGroupId, // Name of the person "Clare" ); /*// Define Toshif * CreatePersonResult friend4 = await faceServiceClient.CreatePersonAsync( * // Id of the person group that the person belonged to * personGroupId, * // Name of the person * "Toshif" * ); */ // Directory contains image files of Anna const string friend1ImageDir = @"D:\Pictures\MyBuddies\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); } } const string friend2ImageDir = @"D:\Pictures\MyBuddies\Toshif\"; foreach (string imagePath in Directory.GetFiles(friend2ImageDir, "*.jpg")) { using (Stream s = File.OpenRead(imagePath)) { // Detect faces in the image and add to Bill await faceServiceClient.AddPersonFaceAsync( personGroupId, friend2.PersonId, s); } } const string friend3ImageDir = @"D:\Pictures\MyBuddies\Clare\"; foreach (string imagePath in Directory.GetFiles(friend3ImageDir, "*.jpg")) { using (Stream s = File.OpenRead(imagePath)) { // Detect faces in the image and add to Clare await faceServiceClient.AddPersonFaceAsync( personGroupId, friend3.PersonId, s); } } /*const string friend4ImageDir = @"D:\Pictures\MyBuddies\Toshif\"; * * foreach (string imagePath in Directory.GetFiles(friend4ImageDir, "*.jpg")) * { * using (Stream s = File.OpenRead(imagePath)) * { * // Detect faces in the image and add to Toshif * await faceServiceClient.AddPersonFaceAsync( * personGroupId, friend4.PersonId, s); * } * } */ Title = String.Format("Success...Group Scaning Completed."); }
private static async Task AddPersonFaceAsync(FaceServiceClient faceServiceClient, CreatePersonResult suspectCreatePersonResult, string imageDir) { foreach (string imagePath in Directory.GetFiles(imageDir, "*.jpg")) { using (Stream s = File.OpenRead(imagePath)) { // Detect faces in the image and add them to correct person await faceServiceClient.AddPersonFaceAsync( Constants.PERSON_GROUP_ID, suspectCreatePersonResult.PersonId, s); } } }
private async Task <bool> add_person_async(string person_group_id) { try { // Check if group already exist // If yes => delete PersonGroup[] person_groups = await face_service_client.ListPersonGroupsAsync(); foreach (PersonGroup pg in person_groups) { if (pg.PersonGroupId == person_group_id) { await face_service_client.DeletePersonGroupAsync(person_group_id); } } // Create group await face_service_client.CreatePersonGroupAsync(person_group_id, person_group_id); // Get all directory in "person dir" foreach (string person_name_dir_path in preson.get_all_person_dir()) { // Get only last directory string dir_person_name = person_name_dir_path.Split(Path.DirectorySeparatorChar).Last();//.Replace("_",""); //Create person with current groupe CreatePersonResult cpr = await face_service_client.CreatePersonAsync(person_group_id, dir_person_name); // TODO Add "*.id" file //add_person_id_file(person_name_dir_path, cpr.PersonId.ToString()); // Get all photos foreach (string person_photo in Directory.EnumerateFiles(person_name_dir_path, "*.*", SearchOption.AllDirectories).Where(n => Path.GetExtension(n) != ".id").ToList()) { if (File.Exists(person_photo)) { Debug.WriteLine($"Add person photo: {person_photo}"); //TODO // PROGRESS update_progress("Add person", $"Process person: {dir_person_name.Split('_')[0]}", ++progress); using (Stream stream = File.OpenRead(person_photo)) { // If the person photo containe no face => throw error try { // Detect faces in the image and add to Anna await face_service_client.AddPersonFaceAsync(person_group_id, cpr.PersonId, stream); } catch { Console.WriteLine("Person photo containe no face"); } } } } } // PROGRESS update_progress("Training group", $"Process group: {person_group_id}", progress); // Training person group await face_service_client.TrainPersonGroupAsync(person_group_id); TrainingStatus trainingStatus = null; while (true) { trainingStatus = await face_service_client.GetPersonGroupTrainingStatusAsync(person_group_id); if (trainingStatus.Status.ToString() != "running") { break; } await Task.Delay(1000); } Debug.WriteLine("Training ok"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); return(false); } return(true); }
public async Task <AddPersistedFaceResult> AddPersonFace(CreatePersonResult personId, Stream faceImg) { return(await AddPersonFace(_personGroupId, personId, faceImg)); }
static async void GroupTest() { FaceServiceClient faceServiceClient = new FaceServiceClient(subscriptionKey.ToString(), "https://northeurope.api.cognitive.microsoft.com/face/v1.0/"); // Create an empty person group string personGroupId = "facegroup"; try { await faceServiceClient.CreatePersonGroupAsync(personGroupId, "My Friends"); Console.WriteLine("Group created"); } catch { Console.WriteLine("Group Exists"); } CreatePersonResult friend1 = await faceServiceClient.CreatePersonAsync( // Id of the person group that the person belonged to personGroupId, // Name of the person "Gunnar" ); CreatePersonResult friend2 = await faceServiceClient.CreatePersonAsync( // Id of the person group that the person belonged to personGroupId, // Name of the person "Hallur" ); var i = 0; const string friend1ImageDir = @"C:\Users\ÓliJón\Pictures\FaceApiTest\Gunnar"; var test = Directory.GetFiles(friend1ImageDir, "*.jpg"); foreach (string imagePath in Directory.GetFiles(friend1ImageDir, "*.jpg")) { i++; using (Stream s = File.OpenRead(imagePath)) { // Detect faces in the image and add to Anna await faceServiceClient.AddPersonFaceAsync( personGroupId, friend1.PersonId, s); Console.WriteLine("Gunnar picture: " + i); } } const string friend2ImageDir = @"C:\Users\ÓliJón\Pictures\FaceApiTest\Hallur"; i = 0; foreach (string imagePath in Directory.GetFiles(friend2ImageDir, "*.jpg")) { i++; using (Stream s = File.OpenRead(imagePath)) { // Detect faces in the image and add to Anna await faceServiceClient.AddPersonFaceAsync( personGroupId, friend2.PersonId, s); Console.WriteLine("Hallur picture: " + i); } } await faceServiceClient.TrainPersonGroupAsync(personGroupId); TrainingStatus trainingStatus = null; while (true) { trainingStatus = await faceServiceClient.GetPersonGroupTrainingStatusAsync(personGroupId); if (trainingStatus.Status.ToString() != "running") { break; } await Task.Delay(3000); } await Task.Delay(3000); string testImageFile = @"C:\Users\ÓliJón\Pictures\FaceApiTest\tester\test.jpg"; 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) { Console.WriteLine("Result of face: {0}", identifyResult.FaceId); if (identifyResult.Candidates.Length == 0) { Console.WriteLine("No one identified"); } else { // Get top 1 among all candidates returned var candidateId = identifyResult.Candidates[0].PersonId; var person = await faceServiceClient.GetPersonAsync(personGroupId, candidateId); Console.WriteLine("Identified as {0}, Confidence: {1}", person.Name, identifyResult.Candidates[0].Confidence); } } } }
public async Task <AddPersistedFaceResult> AddPersonFace(string customGroupId, CreatePersonResult personId, Stream faceImg) { return(await AddPersonFace(customGroupId, personId.PersonId, faceImg)); }
private static async void DetectFaceAndRegister(string personGroupId, CreatePersonResult personResult, string cnp) { //throw new NotImplementedException(); //foreach (var image in Directory.GetFiles(imgPath, "*.*")) //{ // using (Stream S = File.OpenRead(image)) // await faceServiceClient.AddPersonFaceAsync(personGroupId, personResult.PersonId, S); //} var auth = new FirebaseAuthProvider(new FirebaseConfig(apiKey)); var login = await auth.SignInWithEmailAndPasswordAsync(AuthEmail, AuthPassword); var cancellation = new CancellationTokenSource(); var downloadUrl1 = await new FirebaseStorage( Bucket, new FirebaseStorageOptions { AuthTokenAsyncFactory = () => Task.FromResult(login.FirebaseToken), ThrowOnCancel = true }) .Child("user") .Child(cnp) .Child("facial1.jpg").GetDownloadUrlAsync(); string url1 = downloadUrl1.ToString(); var downloadUrl2 = await new FirebaseStorage( Bucket, new FirebaseStorageOptions { AuthTokenAsyncFactory = () => Task.FromResult(login.FirebaseToken), ThrowOnCancel = true }) .Child("user") .Child(cnp) .Child("facial2.jpg"). GetDownloadUrlAsync(); string url2 = downloadUrl2.ToString(); //using (WebClient client = new WebClient()) //{ // // OR // client.DownloadFileAsync(new Uri(url1), @"c:\temp\image35.png"); //} var request1 = WebRequest.Create(url1); using (var response = request1.GetResponse()) using (var stream = response.GetResponseStream()) { await faceServiceClient.AddPersonFaceAsync(personGroupId, personResult.PersonId, stream); } var request2 = WebRequest.Create(url2); using (var response = request2.GetResponse()) using (var stream = response.GetResponseStream()) { await faceServiceClient.AddPersonFaceAsync(personGroupId, personResult.PersonId, stream); } }
async static Task registerPerson(string faceAPIKey, string faceAPIRegion, string personGroupId, string personName, string personImageFolderPath) { Console.WriteLine(" Connect Face API"); var faceServiceClient = new FaceServiceClient(faceAPIKey, $"https://{faceAPIRegion}.api.cognitive.microsoft.com/face/v1.0"); Console.WriteLine(" Create | Get Person Group"); try { await faceServiceClient.DeletePersonGroupAsync(personGroupId); var presonGroup = await faceServiceClient.GetPersonGroupAsync(personGroupId); } catch (FaceAPIException e) { if (e.ErrorCode == "PersonGroupNotFound") { Console.WriteLine(" Create Person Group"); await faceServiceClient.CreatePersonGroupAsync(personGroupId, personGroupId); } else { Console.WriteLine($" Exception - GetPersonGroupAsync: {e.Message}"); return; } } Console.WriteLine(" Add Person"); CreatePersonResult friend1 = await faceServiceClient.CreatePersonAsync( personGroupId, personName ); Console.WriteLine(" Add Images to Person"); foreach (string imagePath in Directory.GetFiles(personImageFolderPath, "*.jpg") .Concat(Directory.GetFiles(personImageFolderPath, "*.png")) .Concat(Directory.GetFiles(personImageFolderPath, "*.gif")) .Concat(Directory.GetFiles(personImageFolderPath, "*.bmp")) .ToArray()) { using (Stream s = File.OpenRead(imagePath)) { // Detect faces in the image and add to Anna await faceServiceClient.AddPersonFaceAsync( personGroupId, friend1.PersonId, s); } } Console.WriteLine(" Start training to Person Group"); await faceServiceClient.TrainPersonGroupAsync(personGroupId); TrainingStatus trainingStatus = null; while (true) { trainingStatus = await faceServiceClient.GetPersonGroupTrainingStatusAsync(personGroupId); if (trainingStatus.Status != Status.Running) { break; } await Task.Delay(1000); } }
private async Task ImportFromFolderAndFilesAsync(StorageFolder autoTrainFolder) { this.commandBar.IsOpen = false; this.progressControl.IsActive = true; List <string> errors = new List <string>(); try { foreach (var folder in await autoTrainFolder.GetFoldersAsync()) { string personName = Util.CapitalizeString(folder.Name.Trim()); if (string.IsNullOrEmpty(personName) || this.PersonsInCurrentGroup.Any(p => p.Name == personName)) { continue; } CreatePersonResult newPersonResult = await FaceServiceHelper.CreatePersonAsync(this.CurrentPersonGroup.PersonGroupId, personName); Person newPerson = new Person { Name = personName, PersonId = newPersonResult.PersonId }; foreach (var photoFile in await folder.GetFilesAsync()) { try { await FaceServiceHelper.AddPersonFaceAsync( this.CurrentPersonGroup.PersonGroupId, newPerson.PersonId, imageStreamCallback : photoFile.OpenStreamForReadAsync, userData : photoFile.Path, targetFace : null); // Force a delay to reduce the chance of hitting API call rate limits await Task.Delay(250); } catch (Exception) { errors.Add(photoFile.Path); } } this.needsTraining = true; this.PersonsInCurrentGroup.Add(newPerson); } } catch (Exception ex) { await Util.GenericApiCallExceptionHandler(ex, "Failure processing the folder and files"); } if (errors.Any()) { await new MessageDialog(string.Join("\n", errors), "Failure importing the folllowing photos").ShowAsync(); } this.progressControl.IsActive = false; }
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; } }
private void MemberService_Saving(IMemberService sender, SaveEventArgs <IMember> e) { var umbracoHelper = new UmbracoHelper(UmbracoContext.Current); var faceServiceClient = new FaceServiceClient(_faceApiKey, _faceApiUrl); foreach (IMember member in e.SavedEntities) { var profileImage = member.GetValue <string>("profilePicture"); if (!string.IsNullOrWhiteSpace(profileImage)) { var profileImageUdi = Udi.Parse(profileImage); var profileImageMedia = umbracoHelper.TypedMedia(profileImageUdi); string fullPath = _fs.GetFullPath(profileImageMedia.Url); /* Stap 2 -> Face API: Delete the person if exists */ if (!string.IsNullOrWhiteSpace(member.GetValue <string>("personId"))) { try { var personId = Guid.Parse(member.GetValue <string>("personId")); AsyncHelpers.RunSync(() => faceServiceClient.DeletePersonAsync(_faceApiGroup, personId)); } catch { // ignored } } /* Stap 3 -> Face API: Detect face and attributes */ using (Stream imageFileStream = _fs.OpenFile(fullPath)) { Face[] detectface = AsyncHelpers.RunSync( () => faceServiceClient.DetectAsync(imageFileStream, false, false, new[] { FaceAttributeType.Age, FaceAttributeType.Gender, FaceAttributeType.Glasses, FaceAttributeType.Makeup, FaceAttributeType.Hair, })); // Getting values and setting the properties on the member string age = detectface.First().FaceAttributes.Age.ToString(); string gender = detectface.First().FaceAttributes.Gender; string glasses = detectface.First().FaceAttributes.Glasses.ToString(); bool eyeMakeup = detectface.First().FaceAttributes.Makeup.EyeMakeup; bool lipMakeup = detectface.First().FaceAttributes.Makeup.LipMakeup; member.SetValue("Age", age); member.SetValue("Gender", gender); member.SetValue("glasses", glasses); member.SetValue("eyeMakeup", eyeMakeup); member.SetValue("lipMakeup", lipMakeup); } // ==> Stap 4 -> Create a person in the persongroup CreatePersonResult person = AsyncHelpers.RunSync(() => faceServiceClient.CreatePersonAsync(_faceApiGroup, member.Name)); member.SetValue("personId", person.PersonId.ToString()); // ==> Stap 5 -> Add face to person and make persistent using (Stream imageFileStream = _fs.OpenFile(fullPath)) { AddPersistedFaceResult result = AsyncHelpers.RunSync(() => faceServiceClient.AddPersonFaceAsync(_faceApiGroup, person.PersonId, imageFileStream)); member.SetValue("faceId", result.PersistedFaceId.ToString()); } } } // ==> Stap 6 -> Train the facegroup AsyncHelpers.RunSync(() => faceServiceClient.TrainPersonGroupAsync(_faceApiGroup)); }
/// <summary> /// POST: api/Messages /// Receive a message from a user and reply to it /// </summary> public async Task <HttpResponseMessage> Post([FromBody] Activity activity) { if (activity.Type == ActivityTypes.Message) { ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); Activity reply = activity.CreateReply(); //Trace.TraceInformation(JsonConvert.SerializeObject(reply, Formatting.Indented)); if (activity.Attachments?.Count > 0 && activity.Attachments.First().ContentType.StartsWith("image")) { //user傳送一張照片 ImageTemplate(reply, activity.Attachments.First().ContentUrl); } //else if(activity.Text == "quick") //Suggestion button //{ // reply.Text = "samplemenu"; // reply.SuggestedActions = new SuggestedActions() // { // Actions = new List<CardAction>() // { // new CardAction(){Title = "USD",Type=ActionTypes.ImBack,Value="USD"}, // new CardAction(){Title = "url",Type=ActionTypes.OpenUrl,Value="www.google.com.tw"} // //new CardAction(){Title = "location",Type=ActionTypes.OpenUrl,Value=""} // } // }; //} else { if (activity.ChannelId == "facebook") { string nametest = activity.Text; bool keyin = nametest.StartsWith("名稱"); var fbData = JsonConvert.DeserializeObject <FBChannelModel>(activity.ChannelData.ToString()); if (fbData.postback != null) { var url = fbData.postback.payload.Split('>')[1]; if (fbData.postback.payload.StartsWith("Face>")) { //faceAPI FaceServiceClient client = new FaceServiceClient("put_your_key_here", "https://westcentralus.api.cognitive.microsoft.com/face/v1.0"); CreatePersonResult result_Person = await client.CreatePersonAsync("security", Global.userid); await client.AddPersonFaceAsync("security", result_Person.PersonId, url); await client.TrainPersonGroupAsync("security"); var result = client.GetPersonGroupTrainingStatusAsync("security"); reply.Text = $"使用者已創立,person_id為:{result_Person.PersonId}"; //var result = await client.DetectAsync(url, true, false); //foreach (var face in result) //{ // var id = face.FaceId; // reply.Text = $"{id}"; //} } //if (fbData.postback.payload.StartsWith("Analyze>")) //{ // //辨識圖片 // VisionServiceClient client = new VisionServiceClient("88b8704fe3bd4483ac755befdc8624db", "https://westcentralus.api.cognitive.microsoft.com/vision/v1.0"); // var result = await client.AnalyzeImageAsync(url, new VisualFeature[] { VisualFeature.Description }); // reply.Text = result.Description.Captions.First().Text; //} else { reply.Text = $"nope"; } } else if (keyin == true) { Global.userid = activity.Text.Trim("名稱".ToCharArray()); reply.Text = $"name set as:{Global.userid}"; } else { reply.Text = $"nope"; } } } await connector.Conversations.ReplyToActivityAsync(reply); } var response = Request.CreateResponse(HttpStatusCode.OK); return(response); }