使用 Amazon SDK for .NET 的 Amazon Rekognition 示例 - Amazon SDK for .NET
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用 Amazon SDK for .NET 的 Amazon Rekognition 示例

以下代码示例演示如何将 Amazon SDK for .NET 与 Amazon Rekognition 结合使用来执行操作和实现常见场景。

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景和跨服务示例的上下文查看操作。

场景是指显示如何通过在同一服务中调用多个函数来完成特定任务的代码示例。

每个示例都包含一个指向的链接 GitHub,您可以在其中找到有关如何在上下文中设置和运行代码的说明。

主题

操作

以下代码示例演示如何使用 Amazon Rekognition 将图像中的人脸与参照图像进行对比。

有关更多信息,请参阅比较图像中的人脸

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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."); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考CompareFaces中的。

以下代码示例演示如何创建 Amazon Rekognition 集合。

有关更多信息,请参阅创建集合

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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}"); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考CreateCollection中的。

以下代码示例演示如何删除 Amazon Rekognition 集合。

有关更多信息,请参阅删除集合

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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}"); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考DeleteCollection中的。

以下代码示例演示如何从 Amazon Rekognition 集合中删除人脸。

有关更多信息,请参阅从集合中删除人脸

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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}"); }); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考DeleteFaces中的。

以下代码示例演示如何描述 Amazon Rekognition 集合。

有关更多信息,请参阅描述集合

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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}"); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考DescribeCollection中的。

以下代码示例演示如何使用 Amazon Rekognition 检测图像中的人脸。

有关更多信息,请参阅检测图像中的人脸

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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

显示图像中所有人脸的边界框信息。

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}"); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考DetectFaces中的。

以下代码示例演示如何使用 Amazon Rekognition 检测图像中的标签。

有关更多信息,请参阅检测图像中的标签

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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

检测存储在计算机上的图像文件中的标签。

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); } } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考DetectLabels中的。

以下代码示例演示如何通过 Amazon Rekognition 检测图像中的审核标签。审核标签可识别可能不适合某些受众的内容。

有关更多信息,请参阅检测不适宜的图像

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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

以下代码示例演示如何使用 Amazon Rekognition 检测图像中的文本。

有关更多信息,请参阅检测图像中的文本

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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); } } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考DetectText中的。

以下代码示例演示如何使用 Amazon Rekognition 获取有关名人的信息。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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); }); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考GetCelebrityInfo中的。

以下代码示例演示如何对图像中的人脸编制索引并将其添加到 Amazon Rekognition 集合中。

有关更多信息,请参阅将人脸添加到集合中

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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}"); } } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考IndexFaces中的。

以下代码示例演示如何列出 Amazon Rekognition 集合。

有关更多信息,请参阅列出集合

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考ListCollections中的。

以下代码示例演示如何列出 Amazon Rekognition 集合中的人脸。

有关更多信息,请参阅列出集合中的人脸

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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)); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考ListFaces中的。

以下代码示例演示如何通过 Amazon Rekognition 识别图像中的名人。

有关更多信息,请参阅识别图像中的名人

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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

以下代码示例演示如何在 Amazon Rekognition 集合中搜索与该集合中另一张人脸匹配的人脸。

有关更多信息,请参阅搜索人脸(人脸 ID)

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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}"); }); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考SearchFaces中的。

以下代码示例演示如何对比参照图像在 Amazon Rekognition 集合中搜索人脸。

有关更多信息,请参阅搜索人脸(图像)

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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}"); }); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考SearchFacesByImage中的。