/// <summary> /// Function to add example faces to a given face list. Will loop through a folder and add all image files in that folder /// </summary> /// <param name="obj"></param> private async void AddExampleFacesToList(object obj) { string personGroupDirectory = Path.Combine(Environment.CurrentDirectory, "PersonGroup"); string[] images = GetImageFiles(personGroupDirectory); try { foreach (string image in images) { using (Stream fileStream = File.OpenRead(image)) { Face[] faces = await _faceServiceClient.DetectAsync(fileStream); FaceRectangle faceRectangle = faces[0].FaceRectangle; AddPersistedFaceResult addFacesResult = await _faceServiceClient.AddFaceToFaceListAsync( FaceListName.ToLower(), fileStream, null, faceRectangle); UpdateFaceGuidsAsync(); } } } catch (FaceAPIException ex) { Debug.WriteLine($"Failed to add faces to face list: {ex.ErrorMessage}"); } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
public async Task <ActionResult> UploadCelebrityPic(HttpPostedFileBase file) { string persistedFaceId = null; string photoUriStr = null; string errorMsg = null; if (file != null && file.ContentLength > 0) { // Make sure the user selected an image file if (!file.ContentType.StartsWith("image")) { TempData["Message"] = "Only image files may be uploaded"; } else { // Save the original image in the "photos" container CloudStorageAccount account = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString")); CloudBlobClient client = account.CreateCloudBlobClient(); CloudBlobContainer container = client.GetContainerReference("celebrity"); CloudBlockBlob photo = container.GetBlockBlobReference(Path.GetFileName(file.FileName)); await photo.UploadFromStreamAsync(file.InputStream); file.InputStream.Seek(0L, SeekOrigin.Begin); // Generate a thumbnail and save it in the "thumbnails" container using (var outputStream = new MemoryStream()) { var settings = new ResizeSettings { MaxWidth = 192, Format = "png" }; ImageBuilder.Current.Build(file.InputStream, outputStream, settings); outputStream.Seek(0L, SeekOrigin.Begin); container = client.GetContainerReference("thumbnails"); CloudBlockBlob thumbnail = container.GetBlockBlobReference(Path.GetFileName(file.FileName)); await thumbnail.UploadFromStreamAsync(outputStream); } // Submit the image to Azure's Computer Vision API FaceServiceClient faceServiceClient = new FaceServiceClient(CloudConfigurationManager.GetSetting("SubscriptionKey")); photoUriStr = photo.Uri.ToString(); try { var result = await faceServiceClient.AddFaceToFaceListAsync("4976", photoUriStr); persistedFaceId = result.PersistedFaceId.ToString(); // Record the image faceID in blob metadata photo.Metadata.Add("faceId", persistedFaceId); await photo.SetMetadataAsync(); } catch (Exception ex) { errorMsg = ((Microsoft.ProjectOxford.Face.FaceAPIException)ex).ErrorMessage; } } } // redirect back to the index action to show the form once again return(RedirectToAction("UploadCelebrityPic", new { error = errorMsg })); }
private async Task <Guid> AddUserToFaceListAsync(string face) { using (var streamFace = new MemoryStream(Convert.FromBase64String(face))) { var persistedFace = await _faceServiceClient.AddFaceToFaceListAsync(_faceListId, streamFace); return(persistedFace.PersistedFaceId); } }
public async Task <dynamic> GetCandidateFiles() { string message = string.Empty; var faceServiceClient = new FaceServiceClient(ServiceKey); FacesCollection.Clear(); DirectoryInfo dir = new DirectoryInfo(Path.Combine(Server.MapPath(directory))); FileInfo[] files = null; files = dir.GetFiles().OrderBy(p => p.CreationTime).ToArray(); if (files.Count() > 0) { _faceListName = Guid.NewGuid().ToString(); await faceServiceClient.CreateFaceListAsync(_faceListName, _faceListName, "face list for sample"); foreach (var item in files) { var imgPath = Server.MapPath(directory) + '\\' + item.Name as string; try { using (var fStream = System.IO.File.OpenRead(imgPath)) { var faces = await faceServiceClient.AddFaceToFaceListAsync(_faceListName, fStream); FacesCollection.Add(new vmFace { ImagePath = imgPath, FileName = item.Name, FilePath = directory + '\\' + item.Name, FaceId = Convert.ToString(faces.PersistedFaceId) }); } } catch (FaceAPIException fe) { //do exception work message = fe.ToString(); } } } else { message = "No files to Detect!! Please Upload Files"; } return(new JsonResult { Data = new { Message = message, FacesCollection = FacesCollection }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); }
/// <summary> /// 上传图片到faceList /// </summary> /// <param name="imgPath"></param> /// <returns></returns> public async Task <AddPersistedFaceResult> ImgToFaceList(string imgPath) { if (!File.Exists(imgPath) || string.IsNullOrEmpty(imgPath)) { return(null); } using (var stream = File.OpenRead(imgPath)) { AddPersistedFaceResult ret = await faceServiceClient.AddFaceToFaceListAsync(faceListId, stream); return(ret); } }
private static async Task <Guid?> AddFaceAsync(Guid faceListId, Stream imageStream) { try { AddPersistedFaceResult faceResult; faceResult = await faceServiceClient.AddFaceToFaceListAsync(faceListId.ToString(), imageStream); return(faceResult.PersistedFaceId); } catch (Exception e) { Console.WriteLine("Face not included in Face List!"); return(null); } }
public async Task RegisterFaceAsync(string faceId, ImageRequest request) { var client = new FaceServiceClient(subscriptionKey: Secrets.CongnitiveServiceFaceApiKey, apiRoot: Consts.CognitiveServiceFaceApiEndPoint); try { await client.GetFaceListAsync(faceId); } catch (FaceAPIException) { // not found await client.CreateFaceListAsync(faceListId : faceId, name : faceId); } await client.AddFaceToFaceListAsync(faceListId : faceId, imageStream : new MemoryStream(request.Image)); }
public async Task <Guid?> AddFaceAsync(Guid faceListId, string imageFilePath) { try { AddPersistedFaceResult faceResult; using (Stream imageFileStream = File.OpenRead(imageFilePath)) { faceResult = await _faceServiceClient.AddFaceToFaceListAsync(faceListId.ToString(), imageFileStream); return(faceResult.PersistedFaceId); } } catch (Exception) { return(null); } }
private static async Task <Guid?> AddFaceAsync(Guid faceListId, string imageFilePath) { try { AddPersistedFaceResult faceResult; using (Stream imageFileStream = File.OpenRead(imageFilePath)) { faceResult = await faceServiceClient.AddFaceToFaceListAsync(faceListId.ToString(), imageFileStream); return(faceResult.PersistedFaceId); } } catch (Exception) { Console.WriteLine("Face not included in Face List!"); return(null); } }
private static async Task <Guid?> AddFaceAsync(Guid faceListId, byte[] image) { try { AddPersistedFaceResult faceResult; using (Stream imageFileStream = new MemoryStream(image)) { faceResult = await faceServiceClient.AddFaceToFaceListAsync(faceListId.ToString(), imageFileStream); return(faceResult.PersistedFaceId); } } catch (Exception ex) { Console.WriteLine("Face not included in Face List! \n Erro: " + ex); return(null); } }
private static async Task <Guid?> AddFaceAsync(Guid faceListId, string imageFilePath) { try { AddPersistedFaceResult faceResult; using (Stream imageFileStream = File.OpenRead(imageFilePath)) { faceServiceClient = new FaceServiceClient(Configuration["FaceAPIKey"], "https://eastus.api.cognitive.microsoft.com/face/v1.0"); faceResult = await faceServiceClient.AddFaceToFaceListAsync(faceListId.ToString(), imageFileStream); return(faceResult.PersistedFaceId); } } catch (Exception) { Console.WriteLine("Face not included in Face List!"); return(null); } }
public async void AddListId(string fileLocation, string subscriptionKey, string name, int edad, string descrip) { using (var fileStream = File.OpenRead(fileLocation)) { try { var client = new FaceServiceClient(subscriptionKey); //var faces1 = await client.DetectAsync(fileStream, true); var faces = await client.AddFaceToFaceListAsync("21122011", fileStream, name); Console.WriteLine(" >> PId: " + faces.PersistedFaceId.ToString()); Form1.PID = faces.PersistedFaceId.ToString(); //ConexionBD.GuardarInfo(name, edad, descrip, Form1.PID); //Comparer.idActual = faces.PersistedFaceId.ToString(); } catch (Exception exception) { Console.WriteLine(exception.ToString()); } fileStream.Close(); } }
private static async Task <Guid?> AddFaceAsync(Guid faceListId, string imageFilePath, FaceRectangle rectangle) { //try //{ // AddPersistedFaceResult faceResult; // faceResult = await faceServiceClient.AddFaceToFaceListAsync(faceListId.ToString(), imageStream, null, rectangle); // return faceResult.PersistedFaceId; //} try { AddPersistedFaceResult faceResult; using (Stream imageFileStream = System.IO.File.OpenRead(imageFilePath)) { faceResult = await faceServiceClient.AddFaceToFaceListAsync(faceListId.ToString(), imageFileStream, null, rectangle); return(faceResult.PersistedFaceId); } } catch (Exception ex) { Console.WriteLine("Face não incluída na lista!"); return(null); } }
public async Task <string> FindSimilarImages() { //Creation of facelist and sending all the images(the images to which we are going to do match) to the facelist _faceListName = Guid.NewGuid().ToString(); // Generating a unique group-id for the entire images var faceServiceClients = new FaceServiceClient(subscriptionKeyValue); //calling the Face API using subscription key try { await faceServiceClients.CreateFaceListAsync(_faceListName, _faceListName, "face_Images"); //Calling the API service'CreateFaceListAsync' to create a facelist with id/name as _faceListName. } catch (FaceAPIException ex) { Errormsg = ex.ErrorMessage; return(RedirectToAction("Error", "Home", new { Errormsg = Errormsg }).ToString()); } DirectoryInfo DirInfo = new DirectoryInfo(@"C:\Image"); Dictionary <string, string> DictionaryListofPersistanceIDAndImagePath = new Dictionary <string, string>();//Dictionary entry for storing the persistance id returned for each image from the Face API service try { foreach (var file in DirInfo.GetFiles("*.jpg")) { string imgPath = @"C:\Image\" + file.ToString(); FileStream fStream = new FileStream(imgPath, FileMode.Open, FileAccess.Read); var faces = await faceServiceClients.AddFaceToFaceListAsync(_faceListName, fStream); //Adding of each image content to the created facelist in the Face API using the service 'AddFaceToFaceListAsync' DictionaryListofPersistanceIDAndImagePath.Add(faces.PersistedFaceId.ToString(), imgPath); //Storing the PersistedFaceId of the image returned by the Face API service and image path in dictionary } } //End catch (FaceAPIException ex) { ViewData["ExceptionMsg"] = ex.ErrorMessage; } // Sending and matching the captured image with the images contained in the facelist // string CapturedImgName = Server.MapPath("~/Image/CapturedImg.jpg"); string CapturedImgName = Server.MapPath("~/test.jpg"); string[] MatchedImgpath; //int MatchedImgcount = 0; using (var fileStream = System.IO.File.OpenRead(CapturedImgName)) { var faceServiceClient = new FaceServiceClient(subscriptionKeyValue); var faces = await faceServiceClient.DetectAsync(fileStream); //Calling the Face API 'DetectAsync' to detect the captured image by sending the content of the captured image // After call it will return a faceid to the captured image foreach (var f in faces) { var faceId = f.FaceId; //Retrive the face id of the captured image const int requestCandidatesCount = 20; // The number of the more confidece images to be rturned.Most matched image have more confidence value. //confidence value is assigned by the Face API service based on the match. try { var result = await faceServiceClient.FindSimilarAsync(faceId, _faceListName, requestCandidatesCount); // Matching the captured image with images by sending faceId and _faceListName to the Face API 'FindSimilarAsync' //The variable result contains the matched image's PersistedFaceId MatchedImgpath = new string[requestCandidatesCount]; //Declare an array with size 'requestCandidatesCount' to store the matched images path // int MatchedImgcount = 0; foreach (var fr in result) //Loop through the PersistedFaceId of matched faces { if (fr.Confidence >= 0.8) //To check whether the confidence value of the matched image is >=0.8 { if (DictionaryListofPersistanceIDAndImagePath.ContainsKey(fr.PersistedFaceId.ToString())) //To check whether the Persistance id is present in the dictionary //if present retrive the curresponding image-path of that PersistedFaceId. { MatchedImgpath[MatchedImgcount] = DictionaryListofPersistanceIDAndImagePath[fr.PersistedFaceId.ToString()]; //Store the image-path in an array.This array contains all the matched image path which have confidence-value >=0.8 MatchedImgcount = MatchedImgcount + 1; } } } } catch (FaceAPIException ex) { ViewData["ExceptionMsg"] = ex.ErrorMessage; } } } if (MatchedImgcount != 0) { return("found"); } else { return("notfound"); } //End }
/// <summary> /// Pick image folder and detect all faces in these images /// </summary> /// <param name="sender">Event sender</param> /// <param name="e">Event arguments</param> private async void FolderPicker_Click(object sender, RoutedEventArgs e) { // Show folder picker System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog(); var result = dlg.ShowDialog(); bool forceContinue = false; if (result == System.Windows.Forms.DialogResult.OK) { // Enumerate all ".jpg" files in the folder, call detect List <Task> tasks = new List <Task>(); FacesCollection.Clear(); TargetFaces.Clear(); FindSimilarCollection.Clear(); SelectedFile = null; // Set the suggestion count is intent to minimum the data preparetion step only, // it's not corresponding to service side constraint const int SuggestionCount = 10; int processCount = 0; MainWindow.Log("Request: Preparing, detecting faces in chosen folder."); MainWindow mainWindow = Window.GetWindow(this) as MainWindow; string subscriptionKey = mainWindow._scenariosControl.SubscriptionKey; var faceServiceClient = new FaceServiceClient(subscriptionKey); _faceListName = Guid.NewGuid().ToString(); await faceServiceClient.CreateFaceListAsync(_faceListName, _faceListName, "face list for sample"); foreach (var img in Directory.EnumerateFiles(dlg.SelectedPath, "*.jpg", SearchOption.AllDirectories)) { tasks.Add(Task.Factory.StartNew( async(obj) => { var imgPath = obj as string; // Call detection using (var fStream = File.OpenRead(imgPath)) { try { var faces = await faceServiceClient.AddFaceToFaceListAsync(_faceListName, fStream); return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, faces)); } catch (FaceAPIException) { // Here we simply ignore all detection failure in this sample // You may handle these exceptions by check the Error.Error.Code and Error.Message property for ClientException object return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, null)); } } }, img).Unwrap().ContinueWith((detectTask) => { var res = detectTask.Result; if (res.Item2 == null) { return; } // Update detected faces on UI this.Dispatcher.Invoke( new Action <ObservableCollection <Face>, string, ClientContract.AddPersistedFaceResult>(UIHelper.UpdateFace), FacesCollection, res.Item1, res.Item2); })); processCount++; if (processCount >= SuggestionCount && !forceContinue) { var continueProcess = System.Windows.Forms.MessageBox.Show("The images loaded have reached the recommended count, may take long time if proceed. Would you like to continue to load images?", "Warning", System.Windows.Forms.MessageBoxButtons.YesNo); if (continueProcess == System.Windows.Forms.DialogResult.Yes) { forceContinue = true; } else { break; } } } await Task.WhenAll(tasks); MainWindow.Log("Response: Success. Total {0} faces are detected.", FacesCollection.Count); } }
private async void AddFaces(object sender, RoutedEventArgs e) { var storageAccount = CloudStorageAccount.Parse(_storageConnectionString); var blobClient = storageAccount.CreateCloudBlobClient(); var container = blobClient.GetContainerReference(_containerName); await container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }); var detectedFaces = 0; var currentFaceListId = ""; var faceServiceClient = new FaceServiceClient(_subscriptionKey); foreach (var blob in await ListBlobsAsync(container)) { Debug.WriteLine(blob.Uri); try { var faces = await faceServiceClient.DetectAsync(blob.Uri.ToString(), true, true, null); foreach (var face in faces) { if (detectedFaces++ == 0) { currentFaceListId = await CreateFaceListAsync(faceServiceClient); Debug.WriteLine(currentFaceListId); } try { var faceData = new FaceData { BlobUrl = blob.Uri.ToString(), FaceRectangle = face.FaceRectangle }; var faceDataJS = JsonConvert.SerializeObject(faceData); var faceResult = await faceServiceClient.AddFaceToFaceListAsync(currentFaceListId, blob.Uri.ToString(), faceDataJS, face.FaceRectangle); Debug.WriteLine(faceResult.PersistedFaceId); } catch (Exception ex) { Debug.WriteLine(ex.Message); } if (detectedFaces >= 1000) { detectedFaces = 0; } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } }
/// <summary> /// Pick image folder and detect all faces in these images /// </summary> /// <param name="sender">Event sender</param> /// <param name="e">Event arguments</param> private async void FolderPicker_Click(object sender, RoutedEventArgs e) { bool groupExists = false; MainWindow mainWindow = Window.GetWindow(this) as MainWindow; string subscriptionKey = mainWindow._scenariosControl.SubscriptionKey; var faceServiceClient = new FaceServiceClient(subscriptionKey); try { MainWindow.Log("Request: Face List {0} will be used to build a person database. Checking whether the face list exists.", _faceListName); await faceServiceClient.GetFaceListAsync(_faceListName); groupExists = true; MainWindow.Log("Response: Face List {0} exists.", _faceListName); } catch (FaceAPIException ex) { if (ex.ErrorCode != "FaceListNotFound") { MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); return; } else { MainWindow.Log("Response: Face List {0} did not exist previously.", _faceListName); } } if (groupExists) { var cleanFaceList = System.Windows.MessageBox.Show(string.Format("Requires a clean up for face list \"{0}\" before setting up a new face list. Click OK to proceed, face list \"{0}\" will be cleared.", _faceListName), "Warning", MessageBoxButton.OKCancel); if (cleanFaceList == MessageBoxResult.OK) { await faceServiceClient.DeleteFaceListAsync(_faceListName); } else { return; } } OpenFaceButton.IsEnabled = false; // Show folder picker System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog(); var result = dlg.ShowDialog(); bool forceContinue = false; if (result == System.Windows.Forms.DialogResult.OK) { // Enumerate all ".jpg" files in the folder, call detect List <Task> tasks = new List <Task>(); FacesCollection.Clear(); TargetFaces.Clear(); FindSimilarMatchPersonCollection.Clear(); FindSimilarMatchFaceCollection.Clear(); SelectedFile = null; // Set the suggestion count is intent to minimum the data preparation step only, // it's not corresponding to service side constraint const int SuggestionCount = 10; int processCount = 0; MainWindow.Log("Request: Preparing, detecting faces in chosen folder."); await faceServiceClient.CreateFaceListAsync(_faceListName, _faceListName, "face list for sample"); var imageList = new ConcurrentBag <string>( Directory.EnumerateFiles(dlg.SelectedPath, "*.*", SearchOption.AllDirectories) .Where(s => s.EndsWith(".jpg") || s.EndsWith(".png") || s.EndsWith(".bmp") || s.EndsWith(".gif"))); string img; int invalidImageCount = 0; while (imageList.TryTake(out img)) { tasks.Add(Task.Factory.StartNew( async(obj) => { var imgPath = obj as string; // Call detection using (var fStream = File.OpenRead(imgPath)) { try { var faces = await faceServiceClient.AddFaceToFaceListAsync(_faceListName, fStream); return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, faces)); } catch (FaceAPIException ex) { // if operation conflict, retry. if (ex.ErrorCode.Equals("ConcurrentOperationConflict")) { imageList.Add(imgPath); return(null); } // if operation cause rate limit exceed, retry. else if (ex.ErrorCode.Equals("RateLimitExceeded")) { imageList.Add(imgPath); return(null); } else if (ex.ErrorMessage.Contains("more than 1 face in the image.")) { Interlocked.Increment(ref invalidImageCount); } // Here we simply ignore all detection failure in this sample // You may handle these exceptions by check the Error.Error.Code and Error.Message property for ClientException object return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, null)); } } }, img).Unwrap().ContinueWith((detectTask) => { var res = detectTask?.Result; if (res?.Item2 == null) { return; } // Update detected faces on UI this.Dispatcher.Invoke( new Action <ObservableCollection <Face>, string, ClientContract.AddPersistedFaceResult>( UIHelper.UpdateFace), FacesCollection, res.Item1, res.Item2); })); processCount++; if (processCount >= SuggestionCount && !forceContinue) { var continueProcess = System.Windows.Forms.MessageBox.Show( "The images loaded have reached the recommended count, may take long time if proceed. Would you like to continue to load images?", "Warning", System.Windows.Forms.MessageBoxButtons.YesNo); if (continueProcess == System.Windows.Forms.DialogResult.Yes) { forceContinue = true; } else { break; } } if (tasks.Count >= _maxConcurrentProcesses || imageList.IsEmpty) { await Task.WhenAll(tasks); tasks.Clear(); } } if (invalidImageCount > 0) { MainWindow.Log("Warning: more or less than one face is detected in {0} images, can not add to face list.", invalidImageCount); } MainWindow.Log("Response: Success. Total {0} faces are detected.", FacesCollection.Count); } GC.Collect(); OpenFaceButton.IsEnabled = true; }
/// <summary> /// Pick image folder and detect all faces in these images /// </summary> /// <param name="sender">Event sender</param> /// <param name="e">Event arguments</param> private async void FolderPicker_Click(object sender, RoutedEventArgs e) { // Show folder picker System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog(); var result = dlg.ShowDialog(); bool forceContinue = false; if (result == System.Windows.Forms.DialogResult.OK) { // Enumerate all ".jpg" files in the folder, call detect List<Task> tasks = new List<Task>(); FacesCollection.Clear(); TargetFaces.Clear(); FindSimilarCollection.Clear(); SelectedFile = null; // Set the suggestion count is intent to minimum the data preparetion step only, // it's not corresponding to service side constraint const int SuggestionCount = 10; int processCount = 0; MainWindow.Log("Request: Preparing, detecting faces in chosen folder."); MainWindow mainWindow = Window.GetWindow(this) as MainWindow; string subscriptionKey = mainWindow._scenariosControl.SubscriptionKey; var faceServiceClient = new FaceServiceClient(subscriptionKey); _faceListName = Guid.NewGuid().ToString(); await faceServiceClient.CreateFaceListAsync(_faceListName, _faceListName, "face list for sample"); foreach (var img in Directory.EnumerateFiles(dlg.SelectedPath, "*.jpg", SearchOption.AllDirectories)) { tasks.Add(Task.Factory.StartNew( async (obj) => { var imgPath = obj as string; // Call detection using (var fStream = File.OpenRead(imgPath)) { try { var faces = await faceServiceClient.AddFaceToFaceListAsync(_faceListName, fStream); return new Tuple<string, ClientContract.AddPersistedFaceResult>(imgPath, faces); } catch (FaceAPIException) { // Here we simply ignore all detection failure in this sample // You may handle these exceptions by check the Error.Error.Code and Error.Message property for ClientException object return new Tuple<string, ClientContract.AddPersistedFaceResult>(imgPath, null); } } }, img).Unwrap().ContinueWith((detectTask) => { var res = detectTask.Result; if (res.Item2 == null) { return; } // Update detected faces on UI this.Dispatcher.Invoke( new Action<ObservableCollection<Face>, string, ClientContract.AddPersistedFaceResult>(UIHelper.UpdateFace), FacesCollection, res.Item1, res.Item2); })); processCount++; if (processCount >= SuggestionCount && !forceContinue) { var continueProcess = System.Windows.Forms.MessageBox.Show("The images loaded have reached the recommended count, may take long time if proceed. Would you like to continue to load images?", "Warning", System.Windows.Forms.MessageBoxButtons.YesNo); if (continueProcess == System.Windows.Forms.DialogResult.Yes) { forceContinue = true; } else { break; } } } await Task.WhenAll(tasks); MainWindow.Log("Response: Success. Total {0} faces are detected.", FacesCollection.Count); } }
public async Task <AddPersistedFaceResult> AddFaceToFaceListAsync(string faceListId, Func <Task <Stream> > imageStreamCallback, FaceRectangle targetFace) { return(await RunTaskWithAutoRetryOnQuotaLimitExceededError <AddPersistedFaceResult>(async() => await faceClient.AddFaceToFaceListAsync(faceListId, await imageStreamCallback(), null, targetFace))); }
async Task <AiResult> MakeRequest(string imageToCheck) { AiResult res = new AiResult(); // imageToCheck = "https://www.liberationnews.org/wp-content/uploads/2015/07/donaldtrump61815.jpg"; EmotionServiceClient emotionServiceClient = new EmotionServiceClient(emotionKey); Emotion[] imageEmotion = await emotionServiceClient.RecognizeAsync(imageToCheck); Console.WriteLine("Feeling: " + imageEmotion[0].Scores.ToRankedList().First().Key); Console.WriteLine("Top score: " + imageEmotion[0].Scores.ToRankedList().First().Value); res.Emotion = string.Format("Unknwn ({0:P2})", 0); float bestScore = 0; foreach (var em in imageEmotion[0].Scores.ToRankedList()) { if (em.Value > bestScore) { bestScore = em.Value; res.Emotion = res.Emotion = string.Format("{0} ({1:P2})", em.Key, em.Value); } } FaceServiceClient faceServiceClient = new FaceServiceClient(faceKey); FaceList trumpList = null; try { trumpList = await faceServiceClient.GetFaceListAsync(faceList); } catch (FaceAPIException apiExp) { if (apiExp.ErrorCode == "FaceListNotFound") { await faceServiceClient.CreateFaceListAsync(faceList, faceList, "A collection of trumps"); trumpList = await faceServiceClient.GetFaceListAsync(faceList); } else { throw apiExp; } } if (trumpList.PersistedFaces.Count() < 5) { await faceServiceClient.AddFaceToFaceListAsync(faceList, "https://www.liberationnews.org/wp-content/uploads/2015/07/donaldtrump61815.jpg"); await faceServiceClient.AddFaceToFaceListAsync(faceList, "http://thefederalist.com/wp-content/uploads/2016/02/trumpie.jpg"); await faceServiceClient.AddFaceToFaceListAsync(faceList, "http://www.redstate.com/uploads/2016/02/donald-trump-is-still-soaring-in-iowa-but-there-are-now-some-clear-warning-signs.jpg"); await faceServiceClient.AddFaceToFaceListAsync(faceList, "http://i.huffpost.com/gen/3706868/images/o-DONALD-TRUMP-FUNNY-facebook.jpg"); await faceServiceClient.AddFaceToFaceListAsync(faceList, "http://media.salon.com/2015/04/donald_trump_thumbsup.jpg"); trumpList = await faceServiceClient.GetFaceListAsync(faceList); } Face[] faceToCompare = await faceServiceClient.DetectAsync(imageToCheck); SimilarPersistedFace[] faces = await faceServiceClient.FindSimilarAsync(faceToCompare[0].FaceId, faceList, FindSimilarMatchMode.matchFace); res.TrumpMatch = String.Format("{0:P2}", 0); if (faces.Count() == 0) { Console.WriteLine("Sorry, nothing compares to you"); } else { double totalConfidence = 0; foreach (SimilarPersistedFace matching in faces) { totalConfidence += matching.Confidence; } double averageConfidence = totalConfidence / faces.Count(); res.TrumpMatch = String.Format("{0:P2}", averageConfidence); Console.WriteLine("Trump comparison: " + res.TrumpMatch); } return(res); }