

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# Amazon S3 버킷에 저장된 이미지 분석
<a name="images-s3"></a>

Amazon Rekognition Image는 Amazon S3 버킷에 저장된 이미지 또는 이미지 바이트로 제공된 이미지를 분석할 수 있습니다.

이 주제에서는 [DetectLabels](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectLabels.html) API 작업을 사용하여 Amazon S3 버킷에 저장된 이미지(JPEG 또는 PNG)에서 객체, 개념, 장면을 감지합니다. [Image](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_Image.html) 입력 파라미터를 사용하여 Amazon Rekognition Image API 작업에 이미지를 전달합니다. `Image` 내에서 [S3Object](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_3Object.html) 객체 속성을 지정하여 S3 버킷에 저장된 이미지를 참조합니다. Amazon S3 버킷에 저장된 이미지의 이미지 바이트는 base64로 인코딩할 필요가 없습니다. 자세한 내용은 [이미지 사양](images-information.md) 단원을 참조하십시오.

## 요청 예제
<a name="images-s3-request"></a>

`DetectLabels`에 대한 이 예제 JSON 요청에서는 `amzn-s3-demo-bucket`이라는 Amazon S3 버킷에서 소스 이미지(`input.jpg`)를 불러옵니다. 단, S3 객체가 있는 S3 버킷의 리전과 Amazon Rekognition Image 작업에 사용하는 리전이 일치해야 한다는 것을 알아 두세요.

```
{
    "Image": {
        "S3Object": {
            "Bucket": "amzn-s3-demo-bucket",
            "Name": "input.jpg"
        }
    },
    "MaxLabels": 10,
    "MinConfidence": 75
}
```

다음 예제에서는 AWS SDKs 및를 사용하여 AWS CLI 를 호출합니다`DetectLabels`. `DetectLabels` 작업 응답에 대한 자세한 내용은 [DetectLabels 응답](labels-detect-labels-image.md#detectlabels-response) 단원을 참조하십시오.

**이미지에서 레이블을 감지하려면**

1. 아직 설정하지 않았다면 다음과 같이 하세요.

   1. `AmazonRekognitionFullAccess` 권한과 `AmazonS3ReadOnlyAccess` 권한을 가진 사용자를 생성하거나 업데이트합니다. 자세한 내용은 [1단계: AWS 계정 설정 및 사용자 생성](setting-up.md#setting-up-iam) 단원을 참조하십시오.

   1.  AWS CLI 및 AWS SDKs를 설치하고 구성합니다. 자세한 내용은 [2단계: AWS CLI 및 AWS SDKs 설정](setup-awscli-sdk.md) 단원을 참조하십시오. API 작업을 직접 호출하는 사용자에게 프로그래밍 방식 액세스에 대한 적절한 권한을 부여했는지 확인하세요. 이를 수행하는 방법에 대한 지침은 [프로그래밍 방식 액세스 권한 부여](sdk-programmatic-access.md) 섹션을 참조하세요.

1. 나무, 집, 보트 등과 같은 객체가 한 개 이상 있는 이미지를 S3 버킷에 업로드합니다. 이미지는 *.jpg* 또는 *.png* 형식이어야 합니다.

   이에 관한 지침은 *Amazon Simple Storage Service 사용 설명서*에서 [Amazon S3에 객체 업로드](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html)를 참조하세요.

1. 다음 예제를 사용하여 `DetectLabels` 작업을 호출합니다.

------
#### [ Java ]

   이 예제는 입력 이미지에서 감지된 레이블 목록을 표시합니다. `bucket` 및 `photo`의 값을 2단계에서 사용한 Amazon S3 버킷과 이미지의 이름으로 바꿉니다.

   ```
   //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 com.amazonaws.samples;
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   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.services.rekognition.model.S3Object;
   import java.util.List;
   
   public class DetectLabels {
   
      public static void main(String[] args) throws Exception {
   
         String photo = "input.jpg";
         String bucket = "bucket";
   
   
         AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
   
         DetectLabelsRequest request = new DetectLabelsRequest()
              .withImage(new Image()
              .withS3Object(new S3Object()
              .withName(photo).withBucket(bucket)))
              .withMaxLabels(10)
              .withMinConfidence(75F);
   
         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();
         }
      }
   }
   ```

------
#### [ AWS CLI ]

   이 예제는 `detect-labels` CLI 작업의 JSON 출력을 표시합니다. `bucket` 및 `photo`의 값을 2단계에서 사용한 Amazon S3 버킷과 이미지의 이름으로 바꿉니다. Rekognition 세션을 생성하는 라인에서 `profile_name`의 값을 개발자 프로필의 이름으로 대체합니다.

   ```
   aws rekognition detect-labels --image '{ "S3Object": { "Bucket": "bucket-name", "Name": "file-name" } }' \
   --features GENERAL_LABELS IMAGE_PROPERTIES \
   --settings '{"ImageProperties": {"MaxDominantColors":1}, {"GeneralLabels":{"LabelInclusionFilters":["Cat"]}}}' \
   --profile profile-name \
   --region us-east-1
   ```

   Windows를 사용하는 경우 아래 예와 같이 따옴표를 이스케이프 처리해 주어야 할 수 있습니다.

   ```
   aws rekognition detect-labels --image "{\"S3Object\":{\"Bucket\":\"bucket-name\",\"Name\":\"file-name\"}}" --features GENERAL_LABELS IMAGE_PROPERTIES --settings "{\"GeneralLabels\":{\"LabelInclusionFilters\":[\"Car\"]}}" --profile profile-name --region us-east-1
   ```

------
#### [ Java V2 ]

   이 코드는 AWS 설명서 SDK 예제 GitHub 리포지토리에서 가져온 것입니다. 전체 예제는 [여기](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectLabelsS3.java)에서 확인하세요.

   ```
   //snippet-start:[rekognition.java2.detect_labels.import]
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   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 software.amazon.awssdk.services.rekognition.model.S3Object;
   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 = "\n" +
               "Usage: " +
               "   <bucket> <image>\n\n" +
               "Where:\n" +
               "   bucket - The name of the Amazon S3 bucket that contains the image (for example, ,ImageBucket)." +
               "   image - The name of the image located in the Amazon S3 bucket (for example, Lake.png). \n\n";
   
           if (args.length != 2) {
               System.out.println(usage);
               System.exit(1);
           }
   
           String bucket = args[0];
           String image = args[1];
           Region region = Region.US_WEST_2;
           RekognitionClient rekClient = RekognitionClient.builder()
               .region(region)
               .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
               .build();
   
           getLabelsfromImage(rekClient, bucket, image);
           rekClient.close();
       }
   
       // snippet-start:[rekognition.java2.detect_labels_s3.main]
       public static void getLabelsfromImage(RekognitionClient rekClient, String bucket, String image) {
   
           try {
               S3Object s3Object = S3Object.builder()
                   .bucket(bucket)
                   .name(image)
                   .build() ;
   
               Image myImage = Image.builder()
                   .s3Object(s3Object)
                   .build();
   
               DetectLabelsRequest detectLabelsRequest = DetectLabelsRequest.builder()
                   .image(myImage)
                   .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 e) {
               System.out.println(e.getMessage());
               System.exit(1);
           }
       }
    // snippet-end:[rekognition.java2.detect_labels.main]
   }
   ```

------
#### [ Python ]

   이 예제는 입력 이미지에서 감지된 레이블을 표시합니다. `bucket` 및 `photo`의 값을 2단계에서 사용한 Amazon S3 버킷과 이미지의 이름으로 바꿉니다. Rekognition 세션을 생성하는 라인에서 `profile_name`의 값을 개발자 프로필의 이름으로 대체합니다.

   ```
   #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(photo, bucket):
   
        session = boto3.Session(profile_name='profile-name')
        client = session.client('rekognition')
   
        response = client.detect_labels(Image={'S3Object':{'Bucket':bucket,'Name':photo}},
        MaxLabels=10,
        # Uncomment to use image properties and filtration settings
        #Features=["GENERAL_LABELS", "IMAGE_PROPERTIES"],
        #Settings={"GeneralLabels": {"LabelInclusionFilters":["Cat"]},
        # "ImageProperties": {"MaxDominantColors":10}}
        )
   
        print('Detected labels for ' + photo)
        print()
        for label in response['Labels']:
            print("Label: " + label['Name'])
            print("Confidence: " + str(label['Confidence']))
            print("Instances:")
   
            for instance in label['Instances']:
                print(" Bounding box")
                print(" Top: " + str(instance['BoundingBox']['Top']))
                print(" Left: " + str(instance['BoundingBox']['Left']))
                print(" Width: " + str(instance['BoundingBox']['Width']))
                print(" Height: " + str(instance['BoundingBox']['Height']))
                print(" Confidence: " + str(instance['Confidence']))
                print()
   
            print("Parents:")
            for parent in label['Parents']:
               print(" " + parent['Name'])
   
            print("Aliases:")
            for alias in label['Aliases']:
                print(" " + alias['Name'])
   
                print("Categories:")
            for category in label['Categories']:
                print(" " + category['Name'])
                print("----------")
                print()
   
        if "ImageProperties" in str(response):
            print("Background:")
            print(response["ImageProperties"]["Background"])
            print()
            print("Foreground:")
            print(response["ImageProperties"]["Foreground"])
            print()
            print("Quality:")
            print(response["ImageProperties"]["Quality"])
            print()
   
        return len(response['Labels'])
   
   def main():
       photo = 'photo-name'
       bucket = 'amzn-s3-demo-bucket'
       label_count = detect_labels(photo, bucket)
       print("Labels detected: " + str(label_count))
   
   if __name__ == "__main__":
       main()
   ```

------
#### [ Node.Js ]

   이 예제는 이미지에서 감지된 레이블에 대한 정보를 표시합니다.

   `photo`의 값을, 하나 이상의 유명 인사 얼굴을 포함하는 이미지 파일의 경로와 파일 이름으로 변경합니다. `bucket`의 값을 제공된 이미지 파일이 저장된 S3 버킷의 이름으로 바꿉니다. `REGION`의 값을 귀하의 계정과 연결된 리전 이름으로 변경하세요. Rekognition 세션을 생성하는 라인에서 `profile_name`의 값을 개발자 프로필의 이름으로 대체합니다.

   ```
   // Import required AWS SDK clients and commands for Node.js
   import { DetectLabelsCommand } from  "@aws-sdk/client-rekognition";
   import  { RekognitionClient } from "@aws-sdk/client-rekognition";
   
   import {fromIni} from '@aws-sdk/credential-providers';
   
   // Set the AWS Region.
   const REGION = "region-name"; //e.g. "us-east-1"
   
   // Create SNS service object.
   const rekogClient = new RekognitionClient({
     region: REGION,
     credentials: fromIni({
          profile: 'profile-name',
     }),
   });
   
   const bucket = 'bucket-name'
   const photo = 'photo-name'
   
   // Set params
   const params = {For example, to grant
       Image: {
         S3Object: {
           Bucket: bucket,
           Name: photo
         },
       },
     }
   
   const detect_labels = async () => {
       try {
           const response = await rekogClient.send(new DetectLabelsCommand(params));
           console.log(response.Labels)
           response.Labels.forEach(label =>{
               console.log(`Confidence: ${label.Confidence}`)
               console.log(`Name: ${label.Name}`)
               console.log('Instances:')
               label.Instances.forEach(instance => {
                   console.log(instance)
               })
               console.log('Parents:')
               label.Parents.forEach(name => {
                   console.log(name)
               })
               console.log("-------")
           })
           return response; // For unit tests.
         } catch (err) {
           console.log("Error", err);
         }
   };
   
   detect_labels();
   ```

------
#### [ .NET ]

   이 예제는 입력 이미지에서 감지된 레이블 목록을 표시합니다. `bucket` 및 `photo`의 값을 2단계에서 사용한 Amazon S3 버킷과 이미지의 이름으로 바꿉니다.

   ```
   //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 Amazon.Rekognition;
   using Amazon.Rekognition.Model;
   
   public class DetectLabels
   {
       public static void Example()
       {
           String photo = "input.jpg";
           String bucket = "amzn-s3-demo-bucket";
   
           AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();
   
           DetectLabelsRequest detectlabelsRequest = new DetectLabelsRequest()
           {
               Image = new Image()
               {
                   S3Object = new S3Object()
                   {
                       Name = photo,
                       Bucket = bucket
                   },
               },
               MaxLabels = 10,
               MinConfidence = 75F
           };
   
           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);
           }
       }
   }
   ```

------
#### [ Ruby ]

   이 예제는 입력 이미지에서 감지된 레이블 목록을 표시합니다. `bucket` 및 `photo`의 값을 2단계에서 사용한 Amazon S3 버킷과 이미지의 이름으로 바꿉니다.

   ```
      # Add to your Gemfile
      # gem 'aws-sdk-rekognition'
      require 'aws-sdk-rekognition'
      credentials = Aws::Credentials.new(
         ENV['AWS_ACCESS_KEY_ID'],
         ENV['AWS_SECRET_ACCESS_KEY']
      )
      bucket = 'bucket' # the bucket name without s3://
      photo  = 'photo' # the name of file
      client   = Aws::Rekognition::Client.new credentials: credentials
      attrs = {
        image: {
          s3_object: {
            bucket: bucket,
            name: photo
          },
        },
        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
   ```

------



## 응답의 예
<a name="images-s3-response"></a>

`DetectLabels`의 응답은 이미지에서 감지된 레이블의 배열과 각각의 해당 신뢰도 수준입니다.

이미지에서 `DetectLabels` 작업을 수행하면 Amazon Rekognition은 다음 예제 응답과 유사한 출력을 반환합니다.

이 응답은 작업에서 여러 개의 레이블(인물, 차량, 자동차)을 감지했음을 보여 줍니다. 각 레이블에는 연결된 신뢰도 수준이 있습니다. 예를 들어 감지 알고리즘 상 이미지에 사람이 포함될 신뢰도는 98.991432%입니다.

또한 응답에는 `Parents` 배열에 레이블의 상위 레이블이 포함되어 있습니다. 예를 들어 자동차 레이블은 차량 및 운송이라는 두 개의 상위 레이블을 갖습니다.

일반적 객체 레이블에 대한 응답은 입력 이미지 상의 레이블 위치에 대한 경계 상자 정보를 포함합니다. 예를 들어 인물 레이블은 두 개의 경계 상자를 포함하는 인스턴스 배열을 갖습니다. 이들은 이미지에서 감지된 두 사람의 위치입니다.

`LabelModelVersion` 필드에는 `DetectLabels`가 사용하는 감지 모델의 버전 번호가 포함됩니다.

`DetectLabels` 작업의 사용에 대한 자세한 내용은 [객체 및 개념 감지](labels.md) 섹션을 참조하세요.

```
{
            
    {
    "Labels": [
        {
            "Name": "Vehicle",
            "Confidence": 99.15271759033203,
            "Instances": [],
            "Parents": [
                {
                    "Name": "Transportation"
                }
            ]
        },
        {
            "Name": "Transportation",
            "Confidence": 99.15271759033203,
            "Instances": [],
            "Parents": []
        },
        {
            "Name": "Automobile",
            "Confidence": 99.15271759033203,
            "Instances": [],
            "Parents": [
                {
                    "Name": "Vehicle"
                },
                {
                    "Name": "Transportation"
                }
            ]
        },
        {
            "Name": "Car",
            "Confidence": 99.15271759033203,
            "Instances": [
                {
                    "BoundingBox": {
                        "Width": 0.10616336017847061,
                        "Height": 0.18528179824352264,
                        "Left": 0.0037978808395564556,
                        "Top": 0.5039216876029968
                    },
                    "Confidence": 99.15271759033203
                },
                {
                    "BoundingBox": {
                        "Width": 0.2429988533258438,
                        "Height": 0.21577216684818268,
                        "Left": 0.7309805154800415,
                        "Top": 0.5251884460449219
                    },
                    "Confidence": 99.1286392211914
                },
                {
                    "BoundingBox": {
                        "Width": 0.14233611524105072,
                        "Height": 0.15528248250484467,
                        "Left": 0.6494812965393066,
                        "Top": 0.5333095788955688
                    },
                    "Confidence": 98.48368072509766
                },
                {
                    "BoundingBox": {
                        "Width": 0.11086395382881165,
                        "Height": 0.10271988064050674,
                        "Left": 0.10355594009160995,
                        "Top": 0.5354844927787781
                    },
                    "Confidence": 96.45606231689453
                },
                {
                    "BoundingBox": {
                        "Width": 0.06254628300666809,
                        "Height": 0.053911514580249786,
                        "Left": 0.46083059906959534,
                        "Top": 0.5573825240135193
                    },
                    "Confidence": 93.65448760986328
                },
                {
                    "BoundingBox": {
                        "Width": 0.10105438530445099,
                        "Height": 0.12226245552301407,
                        "Left": 0.5743985772132874,
                        "Top": 0.534368634223938
                    },
                    "Confidence": 93.06217193603516
                },
                {
                    "BoundingBox": {
                        "Width": 0.056389667093753815,
                        "Height": 0.17163699865341187,
                        "Left": 0.9427769780158997,
                        "Top": 0.5235804319381714
                    },
                    "Confidence": 92.6864013671875
                },
                {
                    "BoundingBox": {
                        "Width": 0.06003860384225845,
                        "Height": 0.06737709045410156,
                        "Left": 0.22409997880458832,
                        "Top": 0.5441341400146484
                    },
                    "Confidence": 90.4227066040039
                },
                {
                    "BoundingBox": {
                        "Width": 0.02848697081208229,
                        "Height": 0.19150497019290924,
                        "Left": 0.0,
                        "Top": 0.5107086896896362
                    },
                    "Confidence": 86.65286254882812
                },
                {
                    "BoundingBox": {
                        "Width": 0.04067881405353546,
                        "Height": 0.03428703173995018,
                        "Left": 0.316415935754776,
                        "Top": 0.5566273927688599
                    },
                    "Confidence": 85.36471557617188
                },
                {
                    "BoundingBox": {
                        "Width": 0.043411049991846085,
                        "Height": 0.0893595889210701,
                        "Left": 0.18293385207653046,
                        "Top": 0.5394920110702515
                    },
                    "Confidence": 82.21705627441406
                },
                {
                    "BoundingBox": {
                        "Width": 0.031183116137981415,
                        "Height": 0.03989990055561066,
                        "Left": 0.2853088080883026,
                        "Top": 0.5579366683959961
                    },
                    "Confidence": 81.0157470703125
                },
                {
                    "BoundingBox": {
                        "Width": 0.031113790348172188,
                        "Height": 0.056484755128622055,
                        "Left": 0.2580395042896271,
                        "Top": 0.5504819750785828
                    },
                    "Confidence": 56.13441467285156
                },
                {
                    "BoundingBox": {
                        "Width": 0.08586374670267105,
                        "Height": 0.08550430089235306,
                        "Left": 0.5128012895584106,
                        "Top": 0.5438792705535889
                    },
                    "Confidence": 52.37760925292969
                }
            ],
            "Parents": [
                {
                    "Name": "Vehicle"
                },
                {
                    "Name": "Transportation"
                }
            ]
        },
        {
            "Name": "Human",
            "Confidence": 98.9914321899414,
            "Instances": [],
            "Parents": []
        },
        {
            "Name": "Person",
            "Confidence": 98.9914321899414,
            "Instances": [
                {
                    "BoundingBox": {
                        "Width": 0.19360728561878204,
                        "Height": 0.2742200493812561,
                        "Left": 0.43734854459762573,
                        "Top": 0.35072067379951477
                    },
                    "Confidence": 98.9914321899414
                },
                {
                    "BoundingBox": {
                        "Width": 0.03801717236638069,
                        "Height": 0.06597328186035156,
                        "Left": 0.9155802130699158,
                        "Top": 0.5010883808135986
                    },
                    "Confidence": 85.02790832519531
                }
            ],
            "Parents": []
        }
    ],
    "LabelModelVersion": "2.0"
}

    
}
```