Ejemplos de Amazon Rekognition con AWS SDK for .NET - Ejemplos de código de AWS SDK

Hay más ejemplos de AWS SDK disponibles en el GitHub repositorio de ejemplos de AWS Doc SDK.

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

Ejemplos de Amazon Rekognition con AWS SDK for .NET

En los siguientes ejemplos de código se muestra cómo ejecutar acciones e implementar escenarios comunes usando AWS SDK for .NET con Amazon Rekognition.

Las acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Mientras las acciones muestran cómo llamar a las funciones de servicio individuales, es posible ver las acciones en contexto en los escenarios relacionados y en los ejemplos entre servicios.

Los escenarios son ejemplos de código que muestran cómo llevar a cabo una tarea específica llamando a varias funciones dentro del mismo servicio.

Cada ejemplo incluye un enlace a GitHub, donde puede encontrar instrucciones sobre cómo configurar y ejecutar el código en su contexto.

Acciones

En el siguiente ejemplo de código se muestra cómo comparar los rostros de una imagen con una imagen de referencia con Amazon Rekognition.

Para obtener más información, consulte Comparación de rostros en imágenes.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

using System; using System.IO; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; /// <summary> /// Uses the Amazon Rekognition Service to compare faces in two images. /// </summary> public class CompareFaces { public static async Task Main() { float similarityThreshold = 70F; string sourceImage = "source.jpg"; string targetImage = "target.jpg"; var rekognitionClient = new AmazonRekognitionClient(); Amazon.Rekognition.Model.Image imageSource = new Amazon.Rekognition.Model.Image(); try { using FileStream fs = new FileStream(sourceImage, FileMode.Open, FileAccess.Read); byte[] data = new byte[fs.Length]; fs.Read(data, 0, (int)fs.Length); imageSource.Bytes = new MemoryStream(data); } catch (Exception) { Console.WriteLine($"Failed to load source image: {sourceImage}"); return; } Amazon.Rekognition.Model.Image imageTarget = new Amazon.Rekognition.Model.Image(); try { using FileStream fs = new FileStream(targetImage, FileMode.Open, FileAccess.Read); byte[] data = new byte[fs.Length]; data = new byte[fs.Length]; fs.Read(data, 0, (int)fs.Length); imageTarget.Bytes = new MemoryStream(data); } catch (Exception ex) { Console.WriteLine($"Failed to load target image: {targetImage}"); Console.WriteLine(ex.Message); return; } var compareFacesRequest = new CompareFacesRequest { SourceImage = imageSource, TargetImage = imageTarget, SimilarityThreshold = similarityThreshold, }; // Call operation var compareFacesResponse = await rekognitionClient.CompareFacesAsync(compareFacesRequest); // Display results compareFacesResponse.FaceMatches.ForEach(match => { ComparedFace face = match.Face; BoundingBox position = face.BoundingBox; Console.WriteLine($"Face at {position.Left} {position.Top} matches with {match.Similarity}% confidence."); }); Console.WriteLine($"Found {compareFacesResponse.UnmatchedFaces.Count} face(s) that did not match."); } }
  • Para obtener más información sobre la API, consulta CompareFacesla Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código se muestra cómo crear una colección de Amazon Rekognition.

Para obtener más información, consulte Creación de una colección.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

using System; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; /// <summary> /// Uses Amazon Rekognition to create a collection to which you can add /// faces using the IndexFaces operation. /// </summary> public class CreateCollection { public static async Task Main() { var rekognitionClient = new AmazonRekognitionClient(); string collectionId = "MyCollection"; Console.WriteLine("Creating collection: " + collectionId); var createCollectionRequest = new CreateCollectionRequest { CollectionId = collectionId, }; CreateCollectionResponse createCollectionResponse = await rekognitionClient.CreateCollectionAsync(createCollectionRequest); Console.WriteLine($"CollectionArn : {createCollectionResponse.CollectionArn}"); Console.WriteLine($"Status code : {createCollectionResponse.StatusCode}"); } }
  • Para obtener más información sobre la API, consulta CreateCollectionla Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código se muestra cómo eliminar una colección de Amazon Rekognition.

Para obtener más información, consulte Eliminación de una colección.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

using System; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; /// <summary> /// Uses the Amazon Rekognition Service to delete an existing collection. /// </summary> public class DeleteCollection { public static async Task Main() { var rekognitionClient = new AmazonRekognitionClient(); string collectionId = "MyCollection"; Console.WriteLine("Deleting collection: " + collectionId); var deleteCollectionRequest = new DeleteCollectionRequest() { CollectionId = collectionId, }; var deleteCollectionResponse = await rekognitionClient.DeleteCollectionAsync(deleteCollectionRequest); Console.WriteLine($"{collectionId}: {deleteCollectionResponse.StatusCode}"); } }
  • Para obtener más información sobre la API, consulta DeleteCollectionla Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código se muestra cómo eliminar rostros de una colección de Amazon Rekognition.

Para obtener más información, consulte Eliminación de rostros de una colección.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; /// <summary> /// Uses the Amazon Rekognition Service to delete one or more faces from /// a Rekognition collection. /// </summary> public class DeleteFaces { public static async Task Main() { string collectionId = "MyCollection"; var faces = new List<string> { "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }; var rekognitionClient = new AmazonRekognitionClient(); var deleteFacesRequest = new DeleteFacesRequest() { CollectionId = collectionId, FaceIds = faces, }; DeleteFacesResponse deleteFacesResponse = await rekognitionClient.DeleteFacesAsync(deleteFacesRequest); deleteFacesResponse.DeletedFaces.ForEach(face => { Console.WriteLine($"FaceID: {face}"); }); } }
  • Para obtener más información sobre la API, consulta DeleteFacesla Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código se muestra cómo describir una colección de Amazon Rekognition.

Para obtener más información, consulte Descripción de una colección.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

using System; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; /// <summary> /// Uses the Amazon Rekognition Service to describe the contents of a /// collection. /// </summary> public class DescribeCollection { public static async Task Main() { var rekognitionClient = new AmazonRekognitionClient(); string collectionId = "MyCollection"; Console.WriteLine($"Describing collection: {collectionId}"); var describeCollectionRequest = new DescribeCollectionRequest() { CollectionId = collectionId, }; var describeCollectionResponse = await rekognitionClient.DescribeCollectionAsync(describeCollectionRequest); Console.WriteLine($"Collection ARN: {describeCollectionResponse.CollectionARN}"); Console.WriteLine($"Face count: {describeCollectionResponse.FaceCount}"); Console.WriteLine($"Face model version: {describeCollectionResponse.FaceModelVersion}"); Console.WriteLine($"Created: {describeCollectionResponse.CreationTimestamp}"); } }
  • Para obtener más información sobre la API, consulta DescribeCollectionla Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código se muestra cómo detectar rostros en una imagen con Amazon Rekognition.

Para obtener más información, consulte Detección de rostros en una imagen.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; /// <summary> /// Uses the Amazon Rekognition Service to detect faces within an image /// stored in an Amazon Simple Storage Service (Amazon S3) bucket. /// </summary> public class DetectFaces { public static async Task Main() { string photo = "input.jpg"; string bucket = "bucket"; var rekognitionClient = new AmazonRekognitionClient(); var detectFacesRequest = new DetectFacesRequest() { Image = new Image() { S3Object = new S3Object() { Name = photo, Bucket = bucket, }, }, // Attributes can be "ALL" or "DEFAULT". // "DEFAULT": BoundingBox, Confidence, Landmarks, Pose, and Quality. // "ALL": See https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Rekognition/TFaceDetail.html Attributes = new List<string>() { "ALL" }, }; try { DetectFacesResponse detectFacesResponse = await rekognitionClient.DetectFacesAsync(detectFacesRequest); bool hasAll = detectFacesRequest.Attributes.Contains("ALL"); foreach (FaceDetail face in detectFacesResponse.FaceDetails) { Console.WriteLine($"BoundingBox: top={face.BoundingBox.Left} left={face.BoundingBox.Top} width={face.BoundingBox.Width} height={face.BoundingBox.Height}"); Console.WriteLine($"Confidence: {face.Confidence}"); Console.WriteLine($"Landmarks: {face.Landmarks.Count}"); Console.WriteLine($"Pose: pitch={face.Pose.Pitch} roll={face.Pose.Roll} yaw={face.Pose.Yaw}"); Console.WriteLine($"Brightness: {face.Quality.Brightness}\tSharpness: {face.Quality.Sharpness}"); if (hasAll) { Console.WriteLine($"Estimated age is between {face.AgeRange.Low} and {face.AgeRange.High} years old."); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } } }

Muestre información de cuadro delimitador de todos los rostros en una imagen.

using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; /// <summary> /// Uses the Amazon Rekognition Service to display the details of the /// bounding boxes around the faces detected in an image. /// </summary> public class ImageOrientationBoundingBox { public static async Task Main() { string photo = @"D:\Development\AWS-Examples\Rekognition\target.jpg"; // "photo.jpg"; var rekognitionClient = new AmazonRekognitionClient(); var image = new Amazon.Rekognition.Model.Image(); try { using var fs = new FileStream(photo, FileMode.Open, FileAccess.Read); byte[] data = null; data = new byte[fs.Length]; fs.Read(data, 0, (int)fs.Length); image.Bytes = new MemoryStream(data); } catch (Exception) { Console.WriteLine("Failed to load file " + photo); return; } int height; int width; // Used to extract original photo width/height using (var imageBitmap = new Bitmap(photo)) { height = imageBitmap.Height; width = imageBitmap.Width; } Console.WriteLine("Image Information:"); Console.WriteLine(photo); Console.WriteLine("Image Height: " + height); Console.WriteLine("Image Width: " + width); try { var detectFacesRequest = new DetectFacesRequest() { Image = image, Attributes = new List<string>() { "ALL" }, }; DetectFacesResponse detectFacesResponse = await rekognitionClient.DetectFacesAsync(detectFacesRequest); detectFacesResponse.FaceDetails.ForEach(face => { Console.WriteLine("Face:"); ShowBoundingBoxPositions( height, width, face.BoundingBox, detectFacesResponse.OrientationCorrection); Console.WriteLine($"BoundingBox: top={face.BoundingBox.Left} left={face.BoundingBox.Top} width={face.BoundingBox.Width} height={face.BoundingBox.Height}"); Console.WriteLine($"The detected face is estimated to be between {face.AgeRange.Low} and {face.AgeRange.High} years old.\n"); }); } catch (Exception ex) { Console.WriteLine(ex.Message); } } /// <summary> /// Display the bounding box information for an image. /// </summary> /// <param name="imageHeight">The height of the image.</param> /// <param name="imageWidth">The width of the image.</param> /// <param name="box">The bounding box for a face found within the image.</param> /// <param name="rotation">The rotation of the face's bounding box.</param> public static void ShowBoundingBoxPositions(int imageHeight, int imageWidth, BoundingBox box, string rotation) { float left; float top; if (rotation == null) { Console.WriteLine("No estimated orientation. Check Exif data."); return; } // Calculate face position based on image orientation. switch (rotation) { case "ROTATE_0": left = imageWidth * box.Left; top = imageHeight * box.Top; break; case "ROTATE_90": left = imageHeight * (1 - (box.Top + box.Height)); top = imageWidth * box.Left; break; case "ROTATE_180": left = imageWidth - (imageWidth * (box.Left + box.Width)); top = imageHeight * (1 - (box.Top + box.Height)); break; case "ROTATE_270": left = imageHeight * box.Top; top = imageWidth * (1 - box.Left - box.Width); break; default: Console.WriteLine("No estimated orientation information. Check Exif data."); return; } // Display face location information. Console.WriteLine($"Left: {left}"); Console.WriteLine($"Top: {top}"); Console.WriteLine($"Face Width: {imageWidth * box.Width}"); Console.WriteLine($"Face Height: {imageHeight * box.Height}"); } }
  • Para obtener más información sobre la API, consulta DetectFacesla Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código se muestra cómo detectar etiquetas en una imagen con Amazon Rekognition.

Para obtener más información, consulte Detección de etiquetas en una imagen.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

using System; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; /// <summary> /// Uses the Amazon Rekognition Service to detect labels within an image /// stored in an Amazon Simple Storage Service (Amazon S3) bucket. /// </summary> public class DetectLabels { public static async Task Main() { string photo = "del_river_02092020_01.jpg"; // "input.jpg"; string bucket = "igsmiths3photos"; // "bucket"; var rekognitionClient = new AmazonRekognitionClient(); var detectlabelsRequest = new DetectLabelsRequest { Image = new Image() { S3Object = new S3Object() { Name = photo, Bucket = bucket, }, }, MaxLabels = 10, MinConfidence = 75F, }; try { DetectLabelsResponse detectLabelsResponse = await rekognitionClient.DetectLabelsAsync(detectlabelsRequest); Console.WriteLine("Detected labels for " + photo); foreach (Label label in detectLabelsResponse.Labels) { Console.WriteLine($"Name: {label.Name} Confidence: {label.Confidence}"); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } }

Detecte las etiquetas en un archivo de imagen que está almacenado en el equipo.

using System; using System.IO; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; /// <summary> /// Uses the Amazon Rekognition Service to detect labels within an image /// stored locally. /// </summary> public class DetectLabelsLocalFile { public static async Task Main() { string photo = "input.jpg"; var image = new Amazon.Rekognition.Model.Image(); try { using var fs = new FileStream(photo, FileMode.Open, FileAccess.Read); byte[] data = null; data = new byte[fs.Length]; fs.Read(data, 0, (int)fs.Length); image.Bytes = new MemoryStream(data); } catch (Exception) { Console.WriteLine("Failed to load file " + photo); return; } var rekognitionClient = new AmazonRekognitionClient(); var detectlabelsRequest = new DetectLabelsRequest { Image = image, MaxLabels = 10, MinConfidence = 77F, }; try { DetectLabelsResponse detectLabelsResponse = await rekognitionClient.DetectLabelsAsync(detectlabelsRequest); Console.WriteLine($"Detected labels for {photo}"); foreach (Label label in detectLabelsResponse.Labels) { Console.WriteLine($"{label.Name}: {label.Confidence}"); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
  • Para obtener más información sobre la API, consulta DetectLabelsla Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código se muestra cómo detectar etiquetas de moderación en una imagen con Amazon Rekognition. Las etiquetas de moderación identifican contenido que puede ser inapropiado para determinados públicos.

Para obtener más información, consulte Detección de imágenes inapropiadas.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

using System; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; /// <summary> /// Uses the Amazon Rekognition Service to detect unsafe content in a /// JPEG or PNG format image. /// </summary> public class DetectModerationLabels { public static async Task Main(string[] args) { string photo = "input.jpg"; string bucket = "bucket"; var rekognitionClient = new AmazonRekognitionClient(); var detectModerationLabelsRequest = new DetectModerationLabelsRequest() { Image = new Image() { S3Object = new S3Object() { Name = photo, Bucket = bucket, }, }, MinConfidence = 60F, }; try { var detectModerationLabelsResponse = await rekognitionClient.DetectModerationLabelsAsync(detectModerationLabelsRequest); Console.WriteLine("Detected labels for " + photo); foreach (ModerationLabel label in detectModerationLabelsResponse.ModerationLabels) { Console.WriteLine($"Label: {label.Name}"); Console.WriteLine($"Confidence: {label.Confidence}"); Console.WriteLine($"Parent: {label.ParentName}"); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
  • Para obtener más información sobre la API, consulta DetectModerationLabelsla Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código se muestra cómo detectar texto en una imagen con Amazon Rekognition.

Para obtener más información, consulte Detección de texto en una imagen.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

using System; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; /// <summary> /// Uses the Amazon Rekognition Service to detect text in an image. The /// example was created using the AWS SDK for .NET version 3.7 and .NET /// Core 5.0. /// </summary> public class DetectText { public static async Task Main() { string photo = "Dad_photographer.jpg"; // "input.jpg"; string bucket = "igsmiths3photos"; // "bucket"; var rekognitionClient = new AmazonRekognitionClient(); var detectTextRequest = new DetectTextRequest() { Image = new Image() { S3Object = new S3Object() { Name = photo, Bucket = bucket, }, }, }; try { DetectTextResponse detectTextResponse = await rekognitionClient.DetectTextAsync(detectTextRequest); Console.WriteLine($"Detected lines and words for {photo}"); detectTextResponse.TextDetections.ForEach(text => { Console.WriteLine($"Detected: {text.DetectedText}"); Console.WriteLine($"Confidence: {text.Confidence}"); Console.WriteLine($"Id : {text.Id}"); Console.WriteLine($"Parent Id: {text.ParentId}"); Console.WriteLine($"Type: {text.Type}"); }); } catch (Exception e) { Console.WriteLine(e.Message); } } }
  • Para obtener más información sobre la API, consulta DetectTextla Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código se muestra cómo obtener información sobre famosos de Amazon Rekognition.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

using System; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; /// <summary> /// Shows how to use Amazon Rekognition to retrieve information about the /// celebrity identified by the supplied celebrity Id. /// </summary> public class CelebrityInfo { public static async Task Main() { string celebId = "nnnnnnnn"; var rekognitionClient = new AmazonRekognitionClient(); var celebrityInfoRequest = new GetCelebrityInfoRequest { Id = celebId, }; Console.WriteLine($"Getting information for celebrity: {celebId}"); var celebrityInfoResponse = await rekognitionClient.GetCelebrityInfoAsync(celebrityInfoRequest); // Display celebrity information. Console.WriteLine($"celebrity name: {celebrityInfoResponse.Name}"); Console.WriteLine("Further information (if available):"); celebrityInfoResponse.Urls.ForEach(url => { Console.WriteLine(url); }); } }
  • Para obtener más información sobre la API, consulta GetCelebrityInfola Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código se muestra cómo indizar los rostros de una imagen y agregarlos a una colección de Amazon Rekognition.

Para obtener más información, consulte Adición de rostros a una colección.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; /// <summary> /// Uses the Amazon Rekognition Service to detect faces in an image /// that has been uploaded to an Amazon Simple Storage Service (Amazon S3) /// bucket and then adds the information to a collection. /// </summary> public class AddFaces { public static async Task Main() { string collectionId = "MyCollection2"; string bucket = "doc-example-bucket"; string photo = "input.jpg"; var rekognitionClient = new AmazonRekognitionClient(); var image = new Image { S3Object = new S3Object { Bucket = bucket, Name = photo, }, }; var indexFacesRequest = new IndexFacesRequest { Image = image, CollectionId = collectionId, ExternalImageId = photo, DetectionAttributes = new List<string>() { "ALL" }, }; IndexFacesResponse indexFacesResponse = await rekognitionClient.IndexFacesAsync(indexFacesRequest); Console.WriteLine($"{photo} added"); foreach (FaceRecord faceRecord in indexFacesResponse.FaceRecords) { Console.WriteLine($"Face detected: Faceid is {faceRecord.Face.FaceId}"); } } }
  • Para obtener más información sobre la API, consulta IndexFacesla Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código se muestra cómo enumerar colecciones de Amazon Rekognition.

Para obtener más información, consulte Enumerar colecciones.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

using System; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; /// <summary> /// Uses Amazon Rekognition to list the collection IDs in the /// current account. /// </summary> public class ListCollections { public static async Task Main() { var rekognitionClient = new AmazonRekognitionClient(); Console.WriteLine("Listing collections"); int limit = 10; var listCollectionsRequest = new ListCollectionsRequest { MaxResults = limit, }; var listCollectionsResponse = new ListCollectionsResponse(); do { if (listCollectionsResponse is not null) { listCollectionsRequest.NextToken = listCollectionsResponse.NextToken; } listCollectionsResponse = await rekognitionClient.ListCollectionsAsync(listCollectionsRequest); listCollectionsResponse.CollectionIds.ForEach(id => { Console.WriteLine(id); }); } while (listCollectionsResponse.NextToken is not null); } }
  • Para obtener más información sobre la API, consulta ListCollectionsla Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código se muestra cómo enumerar los rostros de una colección de Amazon Rekognition.

Para obtener más información, consulte Enumerar rostros en una colección.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

using System; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; /// <summary> /// Uses the Amazon Rekognition Service to retrieve the list of faces /// stored in a collection. /// </summary> public class ListFaces { public static async Task Main() { string collectionId = "MyCollection2"; var rekognitionClient = new AmazonRekognitionClient(); var listFacesResponse = new ListFacesResponse(); Console.WriteLine($"Faces in collection {collectionId}"); var listFacesRequest = new ListFacesRequest { CollectionId = collectionId, MaxResults = 1, }; do { listFacesResponse = await rekognitionClient.ListFacesAsync(listFacesRequest); listFacesResponse.Faces.ForEach(face => { Console.WriteLine(face.FaceId); }); listFacesRequest.NextToken = listFacesResponse.NextToken; } while (!string.IsNullOrEmpty(listFacesResponse.NextToken)); } }
  • Para obtener más información sobre la API, consulta ListFacesla Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código se muestra cómo reconocer famosos en una imagen con Amazon Rekognition.

Para obtener más información, consulte Reconocimiento de famosos en una imagen.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

using System; using System.IO; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; /// <summary> /// Shows how to use Amazon Rekognition to identify celebrities in a photo. /// </summary> public class CelebritiesInImage { public static async Task Main(string[] args) { string photo = "moviestars.jpg"; var rekognitionClient = new AmazonRekognitionClient(); var recognizeCelebritiesRequest = new RecognizeCelebritiesRequest(); var img = new Amazon.Rekognition.Model.Image(); byte[] data = null; try { using var fs = new FileStream(photo, FileMode.Open, FileAccess.Read); data = new byte[fs.Length]; fs.Read(data, 0, (int)fs.Length); } catch (Exception) { Console.WriteLine($"Failed to load file {photo}"); return; } img.Bytes = new MemoryStream(data); recognizeCelebritiesRequest.Image = img; Console.WriteLine($"Looking for celebrities in image {photo}\n"); var recognizeCelebritiesResponse = await rekognitionClient.RecognizeCelebritiesAsync(recognizeCelebritiesRequest); Console.WriteLine($"{recognizeCelebritiesResponse.CelebrityFaces.Count} celebrity(s) were recognized.\n"); recognizeCelebritiesResponse.CelebrityFaces.ForEach(celeb => { Console.WriteLine($"Celebrity recognized: {celeb.Name}"); Console.WriteLine($"Celebrity ID: {celeb.Id}"); BoundingBox boundingBox = celeb.Face.BoundingBox; Console.WriteLine($"position: {boundingBox.Left} {boundingBox.Top}"); Console.WriteLine("Further information (if available):"); celeb.Urls.ForEach(url => { Console.WriteLine(url); }); }); Console.WriteLine($"{recognizeCelebritiesResponse.UnrecognizedFaces.Count} face(s) were unrecognized."); } }
  • Para obtener más información sobre la API, consulta RecognizeCelebritiesla Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código se muestra cómo buscar rostros en una colección de Amazon Rekognition que coincidan con otro rostro de la colección.

Para obtener más información, consulte Búsqueda de un rostro (ID de rostro).

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

using System; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; /// <summary> /// Uses the Amazon Rekognition Service to find faces in an image that /// match the face Id provided in the method request. /// </summary> public class SearchFacesMatchingId { public static async Task Main() { string collectionId = "MyCollection"; string faceId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; var rekognitionClient = new AmazonRekognitionClient(); // Search collection for faces matching the face id. var searchFacesRequest = new SearchFacesRequest { CollectionId = collectionId, FaceId = faceId, FaceMatchThreshold = 70F, MaxFaces = 2, }; SearchFacesResponse searchFacesResponse = await rekognitionClient.SearchFacesAsync(searchFacesRequest); Console.WriteLine("Face matching faceId " + faceId); Console.WriteLine("Matche(s): "); searchFacesResponse.FaceMatches.ForEach(face => { Console.WriteLine($"FaceId: {face.Face.FaceId} Similarity: {face.Similarity}"); }); } }
  • Para obtener más información sobre la API, consulta SearchFacesla Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código se muestra cómo buscar rostros en una colección de Amazon Rekognition en comparación con una imagen de referencia.

Para obtener más información, consulte Búsqueda de un rostro (imagen).

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

using System; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; /// <summary> /// Uses the Amazon Rekognition Service to search for images matching those /// in a collection. /// </summary> public class SearchFacesMatchingImage { public static async Task Main() { string collectionId = "MyCollection"; string bucket = "bucket"; string photo = "input.jpg"; var rekognitionClient = new AmazonRekognitionClient(); // Get an image object from S3 bucket. var image = new Image() { S3Object = new S3Object() { Bucket = bucket, Name = photo, }, }; var searchFacesByImageRequest = new SearchFacesByImageRequest() { CollectionId = collectionId, Image = image, FaceMatchThreshold = 70F, MaxFaces = 2, }; SearchFacesByImageResponse searchFacesByImageResponse = await rekognitionClient.SearchFacesByImageAsync(searchFacesByImageRequest); Console.WriteLine("Faces matching largest face in image from " + photo); searchFacesByImageResponse.FaceMatches.ForEach(face => { Console.WriteLine($"FaceId: {face.Face.FaceId}, Similarity: {face.Similarity}"); }); } }
  • Para obtener más información sobre la API, consulta SearchFacesByImagela Referencia AWS SDK for .NET de la API.