分析從本機檔案系統載入的映像 - Amazon Rekognition

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

分析從本機檔案系統載入的映像

Amazon Rekognition Image 操作可以分析做為映像位元組提供的映像,或存放在 Amazon S3 儲存貯體中的映像。

這些主題提供範例,其示範透過使用從本機檔案系統載入的檔案,將映像位元組提供給 Amazon Rekognition Image API 操作。您可以使用 映像 輸入參數,將映像位元組傳遞至 Amazon Rekognition API 操作。在 Image 內,指定 Bytes 屬性,以傳遞 base64 編碼的映像位元組。

透過使用 Bytes 輸入參數傳遞至 Amazon Rekognition API 操作的映像,必須經過 Base64 編碼。這些範例使用的 AWS 開發套件,會自動以 base64 編碼映像。在呼叫 Amazon Rekognition API 操作前,您不需要再編碼映像位元組。如需詳細資訊,請參閱 映像規格

在這個範例中,JSON 請求 DetectLabels,來源映像位元組以 Bytes 輸入參數傳遞。

{ "Image": { "Bytes": "/9j/4AAQSk....." }, "MaxLabels": 10, "MinConfidence": 77 }

下列範例使用各種 AWS 開發套件和 AWS CLI 呼叫 DetectLabels 操作。如需有關 DetectLabels 操作回應的資訊,請參閱 DetectLabels 回應

如需用戶端 JavaScript 範例,請參閱使用 JavaScript

偵測本機映像中的標籤
  1. 如果您尚未執行:

    1. 建立或更新具有 AmazonRekognitionFullAccessAmazonS3ReadOnlyAccess 許可的使用者。如需詳細資訊,請參閱 步驟 1:設定 AWS 帳戶並建立使用者

    2. 安裝並配置 AWS CLI 和 AWS SDKs。如需詳細資訊,請參閱 步驟 2:設定 AWS CLI 和 AWS SDK

  2. 使用以下範例來呼叫 DetectLabels 操作。

    Java

    下列 Java 範例示範如何從本機檔案系統載入映像,並運用 detectLabels AWS 開發套件操作來偵測標籤。將 photo 的值變更為某個映像檔案的路徑和檔案名稱 (.jpg 或 .png 格式)。

    //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.) package aws.example.rekognition.image; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.List; import com.amazonaws.services.rekognition.AmazonRekognition; import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder; import com.amazonaws.AmazonClientException; import com.amazonaws.services.rekognition.model.AmazonRekognitionException; import com.amazonaws.services.rekognition.model.DetectLabelsRequest; import com.amazonaws.services.rekognition.model.DetectLabelsResult; import com.amazonaws.services.rekognition.model.Image; import com.amazonaws.services.rekognition.model.Label; import com.amazonaws.util.IOUtils; public class DetectLabelsLocalFile { public static void main(String[] args) throws Exception { String photo="input.jpg"; ByteBuffer imageBytes; try (InputStream inputStream = new FileInputStream(new File(photo))) { imageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream)); } AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); DetectLabelsRequest request = new DetectLabelsRequest() .withImage(new Image() .withBytes(imageBytes)) .withMaxLabels(10) .withMinConfidence(77F); try { DetectLabelsResult result = rekognitionClient.detectLabels(request); List <Label> labels = result.getLabels(); System.out.println("Detected labels for " + photo); for (Label label: labels) { System.out.println(label.getName() + ": " + label.getConfidence().toString()); } } catch (AmazonRekognitionException e) { e.printStackTrace(); } } }
    Python

    下列適用於 Python 的 AWS SDK 範例示範如何從本機檔案系統載入映像,並呼叫 detect_labels 操作。將 photo 的值變更為某個映像檔案的路徑和檔案名稱 (.jpg 或 .png 格式)。

    #Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. #PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.) import boto3 def detect_labels_local_file(photo): client=boto3.client('rekognition') with open(photo, 'rb') as image: response = client.detect_labels(Image={'Bytes': image.read()}) print('Detected labels in ' + photo) for label in response['Labels']: print (label['Name'] + ' : ' + str(label['Confidence'])) return len(response['Labels']) def main(): photo='photo' label_count=detect_labels_local_file(photo) print("Labels detected: " + str(label_count)) if __name__ == "__main__": main()
    .NET

    下列 Java 範例示範如何從本機檔案系統載入映像,並運用 DetectLabels 操作來偵測標籤。將 photo 的值變更為某個映像檔案的路徑和檔案名稱 (.jpg 或 .png 格式)。

    //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.) using System; using System.IO; using Amazon.Rekognition; using Amazon.Rekognition.Model; public class DetectLabelsLocalfile { public static void Example() { String photo = "input.jpg"; Amazon.Rekognition.Model.Image image = new Amazon.Rekognition.Model.Image(); try { using (FileStream 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; } AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient(); DetectLabelsRequest detectlabelsRequest = new DetectLabelsRequest() { Image = image, MaxLabels = 10, MinConfidence = 77F }; try { DetectLabelsResponse detectLabelsResponse = rekognitionClient.DetectLabels(detectlabelsRequest); Console.WriteLine("Detected labels for " + photo); foreach (Label label in detectLabelsResponse.Labels) Console.WriteLine("{0}: {1}", label.Name, label.Confidence); } catch (Exception e) { Console.WriteLine(e.Message); } } }
    PHP

    以下 AWS SDK for PHP 件範例說明如何從本機檔案系統載入映像並呼叫 DetectFacesAPI 作業。將 photo 的值變更為某個映像檔案的路徑和檔案名稱 (.jpg 或 .png 格式)。

    <?php //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.) require 'vendor/autoload.php'; use Aws\Rekognition\RekognitionClient; $options = [ 'region' => 'us-west-2', 'version' => 'latest' ]; $rekognition = new RekognitionClient($options); // Get local image $photo = 'input.jpg'; $fp_image = fopen($photo, 'r'); $image = fread($fp_image, filesize($photo)); fclose($fp_image); // Call DetectFaces $result = $rekognition->DetectFaces(array( 'Image' => array( 'Bytes' => $image, ), 'Attributes' => array('ALL') ) ); // Display info for each detected person print 'People: Image position and estimated age' . PHP_EOL; for ($n=0;$n<sizeof($result['FaceDetails']); $n++){ print 'Position: ' . $result['FaceDetails'][$n]['BoundingBox']['Left'] . " " . $result['FaceDetails'][$n]['BoundingBox']['Top'] . PHP_EOL . 'Age (low): '.$result['FaceDetails'][$n]['AgeRange']['Low'] . PHP_EOL . 'Age (high): ' . $result['FaceDetails'][$n]['AgeRange']['High'] . PHP_EOL . PHP_EOL; } ?>
    Ruby

    此範例顯示一份在輸入映像中偵測到的標籤清單。將 photo 的值變更為某個映像檔案的路徑和檔案名稱 (.jpg 或 .png 格式)。

    #Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. #PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.) # gem 'aws-sdk-rekognition' require 'aws-sdk-rekognition' credentials = Aws::Credentials.new( ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'] ) client = Aws::Rekognition::Client.new credentials: credentials photo = 'photo.jpg' path = File.expand_path(photo) # expand path relative to the current directory file = File.read(path) attrs = { image: { bytes: file }, max_labels: 10 } response = client.detect_labels attrs puts "Detected labels for: #{photo}" response.labels.each do |label| puts "Label: #{label.name}" puts "Confidence: #{label.confidence}" puts "Instances:" label['instances'].each do |instance| box = instance['bounding_box'] puts " Bounding box:" puts " Top: #{box.top}" puts " Left: #{box.left}" puts " Width: #{box.width}" puts " Height: #{box.height}" puts " Confidence: #{instance.confidence}" end puts "Parents:" label.parents.each do |parent| puts " #{parent.name}" end puts "------------" puts "" end
    Java V2

    此代碼取自AWS文檔 SDK 示例 GitHub 存儲庫。請參閱此處的完整範例。

    import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rekognition.RekognitionClient; import software.amazon.awssdk.services.rekognition.model.Image; import software.amazon.awssdk.services.rekognition.model.DetectLabelsRequest; import software.amazon.awssdk.services.rekognition.model.DetectLabelsResponse; import software.amazon.awssdk.services.rekognition.model.Label; import software.amazon.awssdk.services.rekognition.model.RekognitionException; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DetectLabels { public static void main(String[] args) { final String usage = """ Usage: <sourceImage> Where: sourceImage - The path to the image (for example, C:\\AWS\\pic1.png).\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String sourceImage = args[0]; Region region = Region.US_EAST_1; RekognitionClient rekClient = RekognitionClient.builder() .region(region) .build(); detectImageLabels(rekClient, sourceImage); rekClient.close(); } public static void detectImageLabels(RekognitionClient rekClient, String sourceImage) { try { InputStream sourceStream = new FileInputStream(sourceImage); SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream); // Create an Image object for the source image. Image souImage = Image.builder() .bytes(sourceBytes) .build(); DetectLabelsRequest detectLabelsRequest = DetectLabelsRequest.builder() .image(souImage) .maxLabels(10) .build(); DetectLabelsResponse labelsResponse = rekClient.detectLabels(detectLabelsRequest); List<Label> labels = labelsResponse.labels(); System.out.println("Detected labels for the given photo"); for (Label label : labels) { System.out.println(label.name() + ": " + label.confidence().toString()); } } catch (RekognitionException | FileNotFoundException e) { System.out.println(e.getMessage()); System.exit(1); } } }