

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

# 이미지 작업
<a name="images"></a>

이 섹션에서는 Amazon Rekognition Image가 이미지에 대해 수행할 수 있는 분석 유형을 다룹니다.
+ [객체 및 장면 감지](labels.md)
+ [얼굴 감지 및 비교](faces.md)
+ [컬렉션에서 얼굴 검색](collections.md)
+ [유명 인사 인식](celebrities.md)
+ [이미지 조절](moderation.md)
+ [이미지 속 텍스트 감지](text-detection.md)

이러한 작업은 Amazon Rekognition Image가 작업에서 발견된 어떠한 정보도 유지하지 않는 비스토리지 API 작업에 의해 수행됩니다. 입력 이미지 바이트는 비 스토리지 API 작업에 의해 유지되지 않습니다. 자세한 내용은 [비스토리지 및 스토리지 API 작업 이해](how-it-works-storage-non-storage.md) 단원을 참조하십시오.

Amazon Rekognition Image는 또한 나중에 검색할 수 있도록 얼굴 메타데이터를 컬렉션에 저장할 수 있습니다. 자세한 내용은 [컬렉션에서 얼굴 검색](collections.md) 단원을 참조하십시오.

이 섹션에서는 Amazon Rekognition Image API 작업을 사용하여 Amazon S3 버킷에 저장된 이미지와 로컬 파일 시스템에서 로드된 이미지 바이트를 분석합니다. 이 섹션에서는 .jpg 이미지에서 이미지 방향 정보를 가져오는 방법에 대해서도 알아봅니다.

 Rekognition은 RGB 채널만 사용하여 추론을 수행합니다. AWS 는 사용자가 디스플레이를 사용하여 비교를 시각적으로(사람이 수동으로) 검사하기 전에 알파 채널을 제거하도록 권장합니다.

**Topics**
+ [이미지 사양](images-information.md)
+ [Amazon S3 버킷에 저장된 이미지 분석](images-s3.md)
+ [로컬 파일 시스템에서 불러온 이미지 분석](images-bytes.md)
+ [경계 상자 표시](images-displaying-bounding-boxes.md)
+ [이미지 방향 및 경계 상자 좌표 가져오기](images-orientation.md)

# 이미지 사양
<a name="images-information"></a>

Amazon Rekognition Image 작업은 .jpg나 .png 형식의 입력 이미지를 분석할 수 있습니다.

직접 호출의 일부로 Amazon Rekognition Image 작업에 이미지 바이트를 전달하거나 기존 Amazon S3 객체를 참조합니다. Amazon S3 버킷에 저장된 이미지를 분석하는 예제는 [Amazon S3 버킷에 저장된 이미지 분석](images-s3.md) 섹션을 참조하세요. 이미지 바이트를 Amazon Rekognition Image API 작업으로 전달하는 예제는 [로컬 파일 시스템에서 불러온 이미지 분석](images-bytes.md) 섹션을 참조하세요.

HTTP를 사용하여 Amazon Rekognition Image 작업의 일부로 이미지 바이트를 전달하는 경우 이미지 바이트는 base64로 인코딩된 문자열이어야 합니다. AWS SDK를 사용하여 API 작업 호출의 일부로 이미지 바이트를 전달하는 경우 이미지 바이트를 base64로 인코딩해야 하는지 여부는 사용하는 언어에 따라 달라집니다.

다음 AWS SDKs는 자동으로 이미지를 base64 인코딩하므로 Amazon Rekognition Image API 작업을 호출하기 전에 이미지 바이트를 인코딩할 필요가 없습니다.
+ Java
+ JavaScript
+ Python
+ PHP

다른 AWS SDK를 사용하는 경우 Rekognition API 작업을 직접 호출할 때 이미지 형식 오류가 발생하면 이미지 바이트를 Rekognition API 작업에 전달하기 전에 base64로 인코딩하세요.

 AWS CLI 를 사용하여 Amazon Rekognition Image 작업을 호출하는 경우 호출의 일부로 이미지 바이트를 전달하는 것은 지원되지 않습니다. 먼저 이미지를 Amazon S3 버킷에 업로드한 다음 업로드된 이미지를 참조하는 작업을 호출해야 합니다.

**참고**  
이미지 바이트 대신 `S3Object`에 저장된 이미지를 전달하면 이미지를 base64로 인코딩할 필요가 없습니다.

Amazon Rekognition Image 작업의 지연 시간을 최소화하는 방법에 대한 자세한 내용은 [Amazon Rekognition Image 작업 지연 시간](operation-latency.md) 섹션을 참조하세요.

## 이미지 방향 수정
<a name="images-image-orientation-correction"></a>

여러 Rekognition API 작업에서는 분석된 이미지의 방향이 반환됩니다. 이미지 방향을 알면 이미지 방향을 전환하여 표시할 수 있으므로 중요합니다. 얼굴을 분석하는 Rekognition API 작업은 이미지 속의 얼굴 위치에 대한 경계 상자도 반환합니다. 경계 상자를 사용하여 이미지의 얼굴 주위에 상자를 표시할 수 있습니다. 반환된 경계 상자 좌표는 이미지 방향의 영향을 받으며 얼굴 주위에 상자를 올바르게 표시하려면 경계 상자 좌표를 변환해야 할 수도 있습니다. 자세한 내용은 [이미지 방향 및 경계 상자 좌표 가져오기](images-orientation.md) 단원을 참조하십시오.

## 이미지 크기 조정
<a name="images-image-sizing"></a>

분석 중에 Amazon Rekognition은 특정 모델 또는 알고리즘에 가장 적합한 사전 정의된 범위 세트를 사용하여 내부적으로 이미지 크기를 조정합니다. 이로 인해 Amazon Rekognition은 입력 이미지의 해상도에 따라 다른 수의 객체를 감지하거나 다른 결과를 내놓을 수 있습니다. 예를 들어 이미지가 두 개 있다고 가정하겠습니다. 첫 번째 이미지의 해상도는 1024x768픽셀입니다. 첫 번째 이미지의 크기가 조정된 버전인 두 번째 이미지의 해상도는 640x480픽셀입니다. [DetectLabels](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectLabels.html)에 이미지를 제출하는 경우 `DetectLabels`에 보낸 두 직접 호출의 응답이 약간 다를 수 있습니다.

# 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"
}

    
}
```

# 로컬 파일 시스템에서 불러온 이미지 분석
<a name="images-bytes"></a>

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

이 주제에서는 로컬 파일 시스템에서 로드된 파일을 사용하여 이미지 바이트를 Amazon Rekognition Image API 작업에 제공하는 예제를 설명합니다. [Image](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_Image.html) 입력 파라미터를 사용하여 Amazon Rekognition Image API 작업에 이미지 바이트를 전달합니다. `Image`에서 `Bytes` 속성을 지정하여 base64로 인코딩된 이미지 바이트를 전달합니다.

`Bytes` 입력 파라미터를 사용하여 Amazon Rekognition API 작업에 전달하는 이미지 바이트는 base64로 인코딩해야 합니다. 이러한 예제의 AWS SDK는 자동으로 base64 인코딩 이미지를 사용합니다. Amazon Rekognition API 작업을 직접 호출하기 전에 이미지 바이트를 인코딩할 필요가 없습니다. 자세한 내용은 [이미지 사양](images-information.md) 단원을 참조하십시오.

`DetectLabels`에 대한 이 예제 JSON 요청에서 소스 이미지 바이트는 `Bytes` 입력 파라미터로 전달됩니다.

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

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

클라이언트 JavaScript 예제는 [JavaScript 사용](image-bytes-javascript.md) 단원을 참조하십시오.

**로컬 이미지의 레이블을 감지하려면**

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) 단원을 참조하십시오.

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

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

   다음 Java 예제는 로컬 파일 시스템에서 이미지를 로드하고 [detectLabels](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/rekognition/model/DetectLabelsRequest.html) AWS SDK 작업을 사용하여 레이블을 감지하는 방법을 보여줍니다. `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](https://aws.amazon.com/sdk-for-python/) 예제는 로컬 파일 시스템에서 이미지를 로드하고 [detect\$1labels](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rekognition.html#Rekognition.Client.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 ]

   다음 예제에서는 로컬 파일 시스템에서 이미지를 로드하고 `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 ]

   다음 [PHP용 AWS SDK](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/welcome.html#getting-started) 예제는 로컬 파일 시스템에서 이미지를 로드하고 [DetectFaces](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-rekognition-2016-06-27.html#detectfaces) API 작업을 호출하는 방법을 보여줍니다. `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 리포지토리에서 가져온 것입니다. 전체 예제는 [여기](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectLabels.java)에서 확인하세요.

   ```
   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.*;
   
   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: <bucketName> <sourceImage>
   
               Where:
                   bucketName - The name of the Amazon S3 bucket where the image is stored
                   sourceImage - The name of the image file (for example, pic1.png).\s
               """;
   
           if (args.length != 2) {
               System.out.println(usage);
               System.exit(1);
           }
   
           String bucketName = args[0] ;
           String sourceImage = args[1] ;
           Region region = Region.US_WEST_2;
           RekognitionClient rekClient = RekognitionClient.builder()
                   .region(region)
                   .build();
   
           detectImageLabels(rekClient, bucketName, sourceImage);
           rekClient.close();
       }
   
       /**
        * Detects the labels in an image stored in an Amazon S3 bucket using the Amazon Rekognition service.
        *
        * @param rekClient     the Amazon Rekognition client used to make the detection request
        * @param bucketName    the name of the Amazon S3 bucket where the image is stored
        * @param sourceImage   the name of the image file to be analyzed
        */
       public static void detectImageLabels(RekognitionClient rekClient, String bucketName, String sourceImage) {
           try {
               S3Object s3ObjectTarget = S3Object.builder()
                       .bucket(bucketName)
                       .name(sourceImage)
                       .build();
   
               Image souImage = Image.builder()
                       .s3Object(s3ObjectTarget)
                       .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 e) {
               System.out.println(e.getMessage());
               System.exit(1);
           }
       }
   }
   ```

------

# JavaScript 사용
<a name="image-bytes-javascript"></a>

다음 JavaScript 웹 페이지 예제를 이용하여 이미지를 선택하고, 이미지에서 감지된 얼굴의 예상 연령을 확인할 수 있습니다. [DetectFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectFaces.html)를 직접 호출하면 추정 연령이 반환됩니다.

선택한 이미지는, 이미지를 base64로 인코딩하는 JavaScript `FileReader.readAsDataURL` 함수를 사용하여 로드됩니다. HTML 캔버스에 이미지를 표시할 때 유용한 기능입니다. 그러나 이렇게 하면 Amazon Rekognition Image 작업으로 전달하기 전에 이미지 바이트 인코딩을 해제해야 합니다. 이 예제에서는 로드된 이미지 바이트를 해독하는 방법을 보여 줍니다. 인코딩된 이미지 바이트가 불편하면 그 대신 로딩된 이미지를 인코딩하지 않는 `FileReader.readAsArrayBuffer`를 사용하십시오. 이렇게 하면 이미지 바이트 인코딩을 먼저 해제하지 않고도 Amazon Rekognition Image 작업을 직접 호출할 수 있습니다. 예제는 [readAsArrayBuffer 사용](#image-bytes-javascript-unencoded) 섹션을 참조하세요.

**JavaScript 예제를 실행하려면**

1. 예제 소스 코드를 편집기에 로드합니다.

1. Amazon Cognito 자격 증명 풀 식별자를 가져옵니다. 자세한 내용은 [Amazon Cognito 자격 증명 풀 식별자 가져오기](#image-bytes-javascript-auth) 단원을 참조하십시오.

1. 예제 코드의 `AnonLog` 함수에서 `IdentityPoolIdToUse`와 `RegionToUse`를 [Amazon Cognito 자격 증명 풀 식별자 가져오기](#image-bytes-javascript-auth)의 9단계에서 기록해 둔 값으로 바꿉니다.

1. `DetectFaces` 함수에서 `RegionToUse`를 이전 단계에서 사용한 값으로 바꿉니다.

1. 예제 소스 코드를 `.html` 파일로 저장합니다.

1. 그 파일을 브라우저에 로드합니다.

1. **찾아보기...** 버튼을 선택하고 얼굴이 하나 이상 들어 있는 이미지를 선택합니다. 이미지에서 감지된 각 얼굴의 예상 연령을 담은 표가 나타납니다.

**참고**  
다음 코드 예제는 더 이상 Amazon Cognito의 일부가 아닌 두 스크립트를 사용합니다. 이러한 파일을 가져오려면 [aws-cognito-sdk.min.js](https://raw.githubusercontent.com/aws/amazon-cognito-identity-js/master/dist/aws-cognito-sdk.js) 및 [amazon-cognito-identity.min.js](https://raw.githubusercontent.com/aws/amazon-cognito-identity-js/master/dist/amazon-cognito-identity.min.js)의 링크를 따라 이동한 후, 각각의 텍스트를 별도의 `.js` 파일로 저장합니다.

## JavaScript 예제 코드
<a name="image-bytes-javascript-code"></a>

다음 코드 예제는 JavaScript V2를 사용합니다. JavaScript V3의 예제는 [AWS 설명서 SDK 예제 GitHub 리포지토리의 예제를 참조하세요.](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascriptv3/example_code/rekognition/estimate-age-example/src)

```
<!--
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.)
-->
<!DOCTYPE html>
<html>
<head>
  <script src="aws-cognito-sdk.min.js"></script>
  <script src="amazon-cognito-identity.min.js"></script>
  <script src="https://sdk.amazonaws.com/js/aws-sdk-2.16.0.min.js"></script>
  <meta charset="UTF-8">
  <title>Rekognition</title>
</head>

<body>
  <H1>Age Estimator</H1>
  <input type="file" name="fileToUpload" id="fileToUpload" accept="image/*">
  <p id="opResult"></p>
</body>
<script>

  document.getElementById("fileToUpload").addEventListener("change", function (event) {
    ProcessImage();
  }, false);
  
  //Calls DetectFaces API and shows estimated ages of detected faces
  function DetectFaces(imageData) {
    AWS.region = "RegionToUse";
    var rekognition = new AWS.Rekognition();
    var params = {
      Image: {
        Bytes: imageData
      },
      Attributes: [
        'ALL',
      ]
    };
    rekognition.detectFaces(params, function (err, data) {
      if (err) console.log(err, err.stack); // an error occurred
      else {
       var table = "<table><tr><th>Low</th><th>High</th></tr>";
        // show each face and build out estimated age table
        for (var i = 0; i < data.FaceDetails.length; i++) {
          table += '<tr><td>' + data.FaceDetails[i].AgeRange.Low +
            '</td><td>' + data.FaceDetails[i].AgeRange.High + '</td></tr>';
        }
        table += "</table>";
        document.getElementById("opResult").innerHTML = table;
      }
    });
  }
  //Loads selected image and unencodes image bytes for Rekognition DetectFaces API
  function ProcessImage() {
    AnonLog();
    var control = document.getElementById("fileToUpload");
    var file = control.files[0];

    // Load base64 encoded image 
    var reader = new FileReader();
    reader.onload = (function (theFile) {
      return function (e) {
        var img = document.createElement('img');
        var image = null;
        img.src = e.target.result;
        var jpg = true;
        try {
          image = atob(e.target.result.split("data:image/jpeg;base64,")[1]);

        } catch (e) {
          jpg = false;
        }
        if (jpg == false) {
          try {
            image = atob(e.target.result.split("data:image/png;base64,")[1]);
          } catch (e) {
            alert("Not an image file Rekognition can process");
            return;
          }
        }
        //unencode image bytes for Rekognition DetectFaces API 
        var length = image.length;
        imageBytes = new ArrayBuffer(length);
        var ua = new Uint8Array(imageBytes);
        for (var i = 0; i < length; i++) {
          ua[i] = image.charCodeAt(i);
        }
        //Call Rekognition  
        DetectFaces(ua);
      };
    })(file);
    reader.readAsDataURL(file);
  }
  //Provides anonymous log on to AWS services
  function AnonLog() {
    
    // Configure the credentials provider to use your identity pool
    AWS.config.region = 'RegionToUse'; // Region
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
      IdentityPoolId: 'IdentityPoolIdToUse',
    });
    // Make the call to obtain credentials
    AWS.config.credentials.get(function () {
      // Credentials will be available when this function is called.
      var accessKeyId = AWS.config.credentials.accessKeyId;
      var secretAccessKey = AWS.config.credentials.secretAccessKey;
      var sessionToken = AWS.config.credentials.sessionToken;
    });
  }
</script>
</html>
```

### readAsArrayBuffer 사용
<a name="image-bytes-javascript-unencoded"></a>

다음은 JavaScript V2를 사용하여 샘플 코드에서 `ProcessImage` 함수를 대안적으로 구현하는 코드 조각입니다. 여기서는 `readAsArrayBuffer`를 사용하여 이미지를 로드하고 `DetectFaces`를 호출합니다. `readAsArrayBuffer`는 로드된 파일을 base64로 인코딩하지 않기 때문에 Amazon Rekognition Image 작업을 직접 호출하기 위해 먼저 이미지 바이트의 인코딩을 해제할 필요가 없습니다.

```
//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.)

function ProcessImage() {
    AnonLog();
    var control = document.getElementById("fileToUpload");
    var file = control.files[0];

    // Load base64 encoded image for display 
    var reader = new FileReader();
    reader.onload = (function (theFile) {
      return function (e) {
        //Call Rekognition  
        AWS.region = "RegionToUse";  
        var rekognition = new AWS.Rekognition();
        var params = {
          Image: {
          Bytes: e.target.result
        },
        Attributes: [
        'ALL',
      ]
    };
    rekognition.detectFaces(params, function (err, data) {
      if (err) console.log(err, err.stack); // an error occurred
      else {
       var table = "<table><tr><th>Low</th><th>High</th></tr>";
        // show each face and build out estimated age table
        for (var i = 0; i < data.FaceDetails.length; i++) {
          table += '<tr><td>' + data.FaceDetails[i].AgeRange.Low +
            '</td><td>' + data.FaceDetails[i].AgeRange.High + '</td></tr>';
        }
        table += "</table>";
        document.getElementById("opResult").innerHTML = table;
      }
    });

      };
    })(file);
    reader.readAsArrayBuffer(file);
  }
```

## Amazon Cognito 자격 증명 풀 식별자 가져오기
<a name="image-bytes-javascript-auth"></a>

간단히 설명하기 위해, 이 예제에서는 익명 Amazon Cognito 자격 증명 풀을 사용하여 Amazon Rekognition Image API에 대한 인증되지 않은 액세스 권한을 제공합니다. 이 방법이 현재 상황에 알맞습니다. 예를 들어, 사용자 로그인을 위한 웹 사이트 무료 액세스 권한 또는 평가판 액세스 권한을 미인증 액세스 권한으로 제공할 수 있습니다. 인증되지 않은 액세스 권한을 제공하려면 Amazon Cognito 사용자 풀을 사용하세요. 자세한 내용은 [Amazon Cognito 사용자 풀](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html)을 참조하세요.

다음 절차에서는 인증되지 않은 자격 증명을 사용할 수 있는 자격 증명 풀을 만드는 방법과 예제 코드에 필요한 자격 증명 풀 식별자를 가져오는 방법을 보여 줍니다.

**자격 증명 풀 식별자를 가져오려면**

1. [Amazon Cognito 콘솔](https://console.aws.amazon.com/cognito/federated)을 엽니다.

1. **새 자격 증명 풀 생성**을 선택합니다.

1. **자격 증명 풀 이름\$1**에 자격 증명 풀의 이름을 입력합니다.

1. **인증되지 않은 자격 증명**에서 **인증되지 않은 자격 증명에 대한 액세스 활성화**를 선택합니다.

1. **풀 생성**을 선택합니다.

1. **세부 정보 보기**를 선택하고 인증되지 않은 자격 증명의 역할 이름을 적어 둡니다.

1. **허용**을 선택합니다.

1. **플랫폼**에서 **JavaScript**를 선택합니다.

1. **AWS 자격 증명 얻기**에서 코드 조각에 표시된 `AWS.config.region` 및 `IdentityPooldId`의 값을 적어 둡니다.

1. IAM 콘솔([https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/))을 엽니다.

1. 탐색 창에서 **역할**을 선택합니다.

1. 6단계에서 적어 둔 역할 이름을 선택합니다.

1. **권한** 탭에서 **정책 연결**을 선택합니다.

1. **AmazonRekognitionReadOnlyAccess**를 선택합니다.

1. **정책 연결**을 선택합니다.

# 경계 상자 표시
<a name="images-displaying-bounding-boxes"></a>

Amazon Rekognition Image 작업은 이미지에서 감지된 항목에 대해 경계 상자 좌표를 반환할 수 있습니다. 예를 들어 [DetectFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectFaces.html) 작업은 이미지에서 감지된 각 얼굴에 대해 경계 상자([BoundingBox](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_BoundingBox.html))를 반환합니다. 경계 상자 좌표를 사용하여 감지된 항목 주위에 상자를 표시할 수 있습니다. 예를 들어 다음 이미지에는 얼굴을 둘러싼 경계 상자가 표시되어 있습니다.

![\[안경을 착용하고 미소 짓는 젊은 여성과 주위의 비눗방울.\]](http://docs.aws.amazon.com/ko_kr/rekognition/latest/dg/images/face.png)


`BoundingBox`에는 다음과 같은 속성이 있습니다.
+ 높이 - 전체 이미지 높이에 대한 비율로서 경계 상자의 높이입니다.
+ 좌측 - 전체 이미지 너비에 대한 비율로서 경계 상자의 좌측 좌표입니다.
+ 상단 - 전체 이미지 높이에 대한 비율로서 경계 상자의 상단 좌표입니다.
+ 너비 - 전체 이미지 너비에 대한 비율로서 경계 상자의 너비입니다.

각 BoundingBox 속성은 0\$11 사이의 값을 가집니다. 각 속성 값은 전체 이미지 너비(`Left` 및 `Width`) 또는 높이(`Height` 및 `Top`)에 대한 비율입니다. 예를 들어 입력 이미지가 700x200픽셀이고, 경계 상자의 상단-좌측 좌표가 350x50픽셀일 경우 API는 `Left` 값 0.5(350/700)와 `Top` 값 0.25(50/200)를 반환합니다.

다음 다이어그램에는 각 경계 상자가 커버하는 이미지 범위가 나와 있습니다.

![\[경계 상자가 이미지의 차원과 어떤 관련이 있는지 보여주는 그래픽입니다.\]](http://docs.aws.amazon.com/ko_kr/rekognition/latest/dg/images/bounding-box.png)


경계 상자를 올바른 위치 및 크기로 표시하려면, (원하는 값에 따라) BoundingBox 값을 이미지 너비 또는 높이에 곱해 픽셀 값을 구해야 합니다. 이 픽셀 값을 사용하여 경계 상자를 표시합니다. 예를 들어 이전 이미지의 픽셀 치수는 608(너비) x 588(높이)입니다. 얼굴의 경계 상자 값은 다음과 같습니다.

```
BoundingBox.Left: 0.3922065
BoundingBox.Top: 0.15567766
BoundingBox.Width: 0.284666
BoundingBox.Height: 0.2930403
```

얼굴 경계 상자의 위치는 다음과 같이 계산됩니다.

`Left coordinate = BoundingBox.Left (0.3922065) * image width (608) = 238`

`Top coordinate = BoundingBox.Top (0.15567766) * image height (588) = 91`

`Face width = BoundingBox.Width (0.284666) * image width (608) = 173`

`Face height = BoundingBox.Height (0.2930403) * image height (588) = 172`

이들 값을 사용하여 얼굴 주위에 경계 상자를 표시합니다.

**참고**  
이미지 방향을 여러 방법으로 설정할 수 있습니다. 애플리케이션이 이미지를 올바르게 표시하기 위해 이미지를 회전해야 할 수 있습니다. 경계 상자 좌표는 이미지의 방향에 영향을 받습니다. 경계 상자를 올바른 위치에 표시하기 위해 좌표를 변환해야 할 수 있습니다. 자세한 내용은 [이미지 방향 및 경계 상자 좌표 가져오기](images-orientation.md) 단원을 참조하십시오.

다음 예제는 [DetectFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectFaces.html)를 직접 호출하여 감지된 얼굴 주위에 경계 상자를 표시하는 방법을 보여줍니다. 예제에서는 이미지 방향이 0도로 설정된 것으로 가정합니다. 또한 Amazon S3 버킷에서 이미지를 다운로드하는 방법도 보여줍니다.

**경계 상자를 표시하는 방법**

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) 단원을 참조하십시오.

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

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

   `bucket`의 값을 이미지 파일이 저장된 Amazon S3 버킷으로 바꿉니다. `photo`의 값을 이미지 파일(.jpg 또는 .png 형식)의 파일 이름으로 바꿉니다.

   ```
    
   //Loads images, detects faces and draws bounding boxes.Determines exif orientation, if necessary.
   package com.amazonaws.samples;
   
   //Import the basic graphics classes.
   import java.awt.*;
   import java.awt.image.BufferedImage;
   import java.util.List;
   import javax.imageio.ImageIO;
   import javax.swing.*;
   
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   
   import com.amazonaws.services.rekognition.model.BoundingBox;
   import com.amazonaws.services.rekognition.model.DetectFacesRequest;
   import com.amazonaws.services.rekognition.model.DetectFacesResult;
   import com.amazonaws.services.rekognition.model.FaceDetail;
   import com.amazonaws.services.rekognition.model.Image;
   import com.amazonaws.services.rekognition.model.S3Object;
   import com.amazonaws.services.s3.AmazonS3;
   import com.amazonaws.services.s3.AmazonS3ClientBuilder;
   import com.amazonaws.services.s3.model.S3ObjectInputStream;
   
   // Calls DetectFaces and displays a bounding box around each detected image.
   public class DisplayFaces extends JPanel {
   
       private static final long serialVersionUID = 1L;
   
       BufferedImage image;
       static int scale;
       DetectFacesResult result;
   
       public DisplayFaces(DetectFacesResult facesResult, BufferedImage bufImage) throws Exception {
           super();
           scale = 1; // increase to shrink image size.
   
           result = facesResult;
           image = bufImage;
   
           
       }
       // Draws the bounding box around the detected faces.
       public void paintComponent(Graphics g) {
           float left = 0;
           float top = 0;
           int height = image.getHeight(this);
           int width = image.getWidth(this);
   
           Graphics2D g2d = (Graphics2D) g; // Create a Java2D version of g.
   
           // Draw the image.
           g2d.drawImage(image, 0, 0, width / scale, height / scale, this);
           g2d.setColor(new Color(0, 212, 0));
   
           // Iterate through faces and display bounding boxes.
           List<FaceDetail> faceDetails = result.getFaceDetails();
           for (FaceDetail face : faceDetails) {
               
               BoundingBox box = face.getBoundingBox();
               left = width * box.getLeft();
               top = height * box.getTop();
               g2d.drawRect(Math.round(left / scale), Math.round(top / scale),
                       Math.round((width * box.getWidth()) / scale), Math.round((height * box.getHeight())) / scale);
               
           }
       }
   
   
       public static void main(String arg[]) throws Exception {
   
           String photo = "photo.png";
           String bucket = "bucket";
           int height = 0;
           int width = 0;
   
           // Get the image from an S3 Bucket
           AmazonS3 s3client = AmazonS3ClientBuilder.defaultClient();
   
           com.amazonaws.services.s3.model.S3Object s3object = s3client.getObject(bucket, photo);
           S3ObjectInputStream inputStream = s3object.getObjectContent();
           BufferedImage image = ImageIO.read(inputStream);
           DetectFacesRequest request = new DetectFacesRequest()
                   .withImage(new Image().withS3Object(new S3Object().withName(photo).withBucket(bucket)));
   
           width = image.getWidth();
           height = image.getHeight();
   
           // Call DetectFaces    
           AmazonRekognition amazonRekognition = AmazonRekognitionClientBuilder.defaultClient();
           DetectFacesResult result = amazonRekognition.detectFaces(request);
           
           //Show the bounding box info for each face.
           List<FaceDetail> faceDetails = result.getFaceDetails();
           for (FaceDetail face : faceDetails) {
   
               BoundingBox box = face.getBoundingBox();
               float left = width * box.getLeft();
               float top = height * box.getTop();
               System.out.println("Face:");
   
               System.out.println("Left: " + String.valueOf((int) left));
               System.out.println("Top: " + String.valueOf((int) top));
               System.out.println("Face Width: " + String.valueOf((int) (width * box.getWidth())));
               System.out.println("Face Height: " + String.valueOf((int) (height * box.getHeight())));
               System.out.println();
   
           }
   
           // Create frame and panel.
           JFrame frame = new JFrame("RotateImage");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           DisplayFaces panel = new DisplayFaces(result, image);
           panel.setPreferredSize(new Dimension(image.getWidth() / scale, image.getHeight() / scale));
           frame.setContentPane(panel);
           frame.pack();
           frame.setVisible(true);
   
       }
   }
   ```

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

   `bucket`의 값을 이미지 파일이 저장된 Amazon S3 버킷으로 바꿉니다. `photo`의 값을 이미지 파일(.jpg 또는 .png 형식)의 파일 이름으로 바꿉니다. Rekognition 세션을 생성하는 라인에서 `profile_name`의 값을 개발자 프로필의 이름으로 대체합니다.

   ```
   import boto3
   import io
   from PIL import Image, ImageDraw
   
   def show_faces(photo, bucket):
   
       session = boto3.Session(profile_name='profile-name')
       client = session.client('rekognition')
   
       # Load image from S3 bucket
       s3_connection = boto3.resource('s3')
       s3_object = s3_connection.Object(bucket, photo)
       s3_response = s3_object.get()
   
       stream = io.BytesIO(s3_response['Body'].read())
       image = Image.open(stream)
   
       # Call DetectFaces
       response = client.detect_faces(Image={'S3Object': {'Bucket': bucket, 'Name': photo}},
                                      Attributes=['ALL'])
   
       imgWidth, imgHeight = image.size
       draw = ImageDraw.Draw(image)
   
       # calculate and display bounding boxes for each detected face
       print('Detected faces for ' + photo)
       for faceDetail in response['FaceDetails']:
           print('The detected face is between ' + str(faceDetail['AgeRange']['Low'])
                 + ' and ' + str(faceDetail['AgeRange']['High']) + ' years old')
   
           box = faceDetail['BoundingBox']
           left = imgWidth * box['Left']
           top = imgHeight * box['Top']
           width = imgWidth * box['Width']
           height = imgHeight * box['Height']
   
           print('Left: ' + '{0:.0f}'.format(left))
           print('Top: ' + '{0:.0f}'.format(top))
           print('Face Width: ' + "{0:.0f}".format(width))
           print('Face Height: ' + "{0:.0f}".format(height))
   
           points = (
               (left, top),
               (left + width, top),
               (left + width, top + height),
               (left, top + height),
               (left, top)
   
           )
           draw.line(points, fill='#00d400', width=2)
   
           # Alternatively can draw rectangle. However you can't set line width.
           # draw.rectangle([left,top, left + width, top + height], outline='#00d400')
   
       image.show()
   
       return len(response['FaceDetails'])
   
   def main():
       bucket = "bucket-name"
       photo = "photo-name"
       faces_count = show_faces(photo, bucket)
       print("faces detected: " + str(faces_count))
   
   if __name__ == "__main__":
       main()
   ```

------
#### [ 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/DisplayFacesFrame.java)에서 확인하세요.

   참고로, `s3`은 AWS SDK Amazon S3 클라이언트를 가리키며 `rekClient`는 AWS SDK Amazon Rekognition 클라이언트를 가리킵니다.

   ```
   //snippet-start:[rekognition.java2.detect_labels.import]
   import java.awt.*;
   import java.awt.image.BufferedImage;
   import java.io.ByteArrayInputStream;
   import java.io.FileNotFoundException;
   import java.io.IOException;
   import java.io.InputStream;
   import java.util.List;
   import javax.imageio.ImageIO;
   import javax.swing.*;
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.core.ResponseBytes;
   import software.amazon.awssdk.core.SdkBytes;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.model.Attribute;
   import software.amazon.awssdk.services.rekognition.model.BoundingBox;
   import software.amazon.awssdk.services.rekognition.model.DetectFacesRequest;
   import software.amazon.awssdk.services.rekognition.model.DetectFacesResponse;
   import software.amazon.awssdk.services.rekognition.model.FaceDetail;
   import software.amazon.awssdk.services.rekognition.model.Image;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   import software.amazon.awssdk.services.s3.S3Client;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.s3.model.GetObjectRequest;
   import software.amazon.awssdk.services.s3.model.GetObjectResponse;
   import software.amazon.awssdk.services.s3.model.S3Exception;
   //snippet-end:[rekognition.java2.detect_labels.import]
   
   /**
   * 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 DisplayFaces extends JPanel {
   
       static DetectFacesResponse result;
       static BufferedImage image;
       static int scale;
   
       public static void main(String[] args) throws Exception {
   
           final String usage = "\n" +
               "Usage: " +
               "   <sourceImage> <bucketName>\n\n" +
               "Where:\n" +
               "   sourceImage - The name of the image in an Amazon S3 bucket (for example, people.png). \n\n" +
               "   bucketName - The name of the Amazon S3 bucket (for example, amzn-s3-demo-bucket). \n\n";
   
           if (args.length != 2) {
               System.out.println(usage);
               System.exit(1);
           }
   
           String sourceImage = args[0];
           String bucketName = args[1];
           Region region = Region.US_EAST_1;
           S3Client s3 = S3Client.builder()
               .region(region)
               .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
               .build();
   
           RekognitionClient rekClient = RekognitionClient.builder()
               .region(region)
               .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
               .build();
   
           displayAllFaces(s3, rekClient, sourceImage, bucketName);
           s3.close();
           rekClient.close();
       }
   
       // snippet-start:[rekognition.java2.display_faces.main]
       public static void displayAllFaces(S3Client s3,
                                          RekognitionClient rekClient,
                                          String sourceImage,
                                          String bucketName) {
           int height;
           int width;
           byte[] data = getObjectBytes (s3, bucketName, sourceImage);
           InputStream is = new ByteArrayInputStream(data);
   
           try {
               SdkBytes sourceBytes = SdkBytes.fromInputStream(is);
               image = ImageIO.read(sourceBytes.asInputStream());
               width = image.getWidth();
               height = image.getHeight();
   
               // Create an Image object for the source image
               software.amazon.awssdk.services.rekognition.model.Image souImage = Image.builder()
                   .bytes(sourceBytes)
                   .build();
   
               DetectFacesRequest facesRequest = DetectFacesRequest.builder()
                   .attributes(Attribute.ALL)
                   .image(souImage)
                   .build();
   
               result = rekClient.detectFaces(facesRequest);
   
               // Show the bounding box info for each face.
               List<FaceDetail> faceDetails = result.faceDetails();
               for (FaceDetail face : faceDetails) {
                   BoundingBox box = face.boundingBox();
                   float left = width * box.left();
                   float top = height * box.top();
                   System.out.println("Face:");
   
                   System.out.println("Left: " + (int) left);
                   System.out.println("Top: " + (int) top);
                   System.out.println("Face Width: " + (int) (width * box.width()));
                   System.out.println("Face Height: " + (int) (height * box.height()));
                   System.out.println();
               }
   
               // Create the frame and panel.
               JFrame frame = new JFrame("RotateImage");
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               DisplayFaces panel = new DisplayFaces(image);
               panel.setPreferredSize(new Dimension(image.getWidth() / scale, image.getHeight() / scale));
               frame.setContentPane(panel);
               frame.pack();
               frame.setVisible(true);
   
           } catch (RekognitionException | FileNotFoundException e) {
               System.out.println(e.getMessage());
               System.exit(1);
           } catch (IOException e) {
              e.printStackTrace();
           }
       }
   
       public static byte[] getObjectBytes (S3Client s3, String bucketName, String keyName) {
   
           try {
               GetObjectRequest objectRequest = GetObjectRequest
                   .builder()
                   .key(keyName)
                   .bucket(bucketName)
                   .build();
   
               ResponseBytes<GetObjectResponse> objectBytes = s3.getObjectAsBytes(objectRequest);
               return objectBytes.asByteArray();
   
           } catch (S3Exception e) {
               System.err.println(e.awsErrorDetails().errorMessage());
               System.exit(1);
           }
           return null;
       }
   
       public DisplayFaces(BufferedImage bufImage) {
           super();
           scale = 1; // increase to shrink image size.
           image = bufImage;
       }
   
       // Draws the bounding box around the detected faces.
       public void paintComponent(Graphics g) {
           float left;
           float top;
           int height = image.getHeight(this);
           int width = image.getWidth(this);
           Graphics2D g2d = (Graphics2D) g; // Create a Java2D version of g.
   
           // Draw the image
           g2d.drawImage(image, 0, 0, width / scale, height / scale, this);
           g2d.setColor(new Color(0, 212, 0));
   
           // Iterate through the faces and display bounding boxes.
           List<FaceDetail> faceDetails = result.faceDetails();
           for (FaceDetail face : faceDetails) {
               BoundingBox box = face.boundingBox();
               left = width * box.left();
               top = height * box.top();
               g2d.drawRect(Math.round(left / scale), Math.round(top / scale),
                       Math.round((width * box.width()) / scale), Math.round((height * box.height())) / scale);
           }
       }
       // snippet-end:[rekognition.java2.display_faces.main]
   }
   ```

------

# 이미지 방향 및 경계 상자 좌표 가져오기
<a name="images-orientation"></a>

Amazon Rekognition Image를 사용하는 애플리케이션은 일반적으로 Amazon Rekognition Image 작업으로 감지된 이미지 및 감지된 얼굴 주위의 상자를 표시해야 합니다. 애플리케이션에서 이미지를 올바르게 표시하려면 이미지의 방향을 알아야 합니다. 이 방향을 수정해야 할 수도 있습니다. 일부 .jpg 파일의 경우 이미지의 교환 이미지 파일 형식(Exif) 메타데이터에 이미지의 방향이 포함됩니다.

얼굴 주위에 상자를 표시하려면 얼굴의 경계 상자에 대한 좌표가 필요합니다. 상자 방향이 올바르지 않으면 해당 좌표를 조정해야 할 수 있습니다. Amazon Rekognition Image의 얼굴 감지 작업은 감지된 각 얼굴에 대한 경계 상자 좌표를 반환하지만 Exif 메타데이터가 없는.jpg 파일의 좌표는 추정하지 않습니다.

다음 예제는 이미지에서 감지된 얼굴의 경계 상자 좌표를 가져오는 방법을 보여줍니다.

이 예제의 정보를 사용하여 이미지의 방향이 올바른지, 경계 상자가 애플리케이션의 올바른 위치에 표시되는지 확인하십시오.

이미지와 경계 상자를 회전하고 표시하는 데 사용되는 코드는 사용하는 언어와 환경에 따라 다르므로 코드에 이미지와 경계 상자를 표시하는 방법이나 Exif 메타데이터에서 방향 정보를 가져오는 방법을 설명하지 않습니다.



## 이미지의 방향 찾기
<a name="images-discovering-image-orientation"></a>

애플리케이션에서 이미지를 올바르게 표시하려면 이미지를 회전해야 할 수 있습니다. 다음 이미지의 방향은 0도이며 올바르게 표시되어 있습니다.

![\[사용자 계정 또는 프로필 이미지를 나타내는 일반 프로필 아이콘입니다.\]](http://docs.aws.amazon.com/ko_kr/rekognition/latest/dg/images/00face.png)


그러나 다음 이미지는 시계 반대 방향으로 90도 회전된 상태입니다. 올바르게 표시하려면 이미지의 방향을 찾고 코드에서 해당 정보를 사용하여 이미지를 0도로 회전해야 합니다.

![\[사용자 계정 또는 프로필 이미지를 나타내는 일반 프로필 아이콘으로, 시계 반대 방향으로 90도 회전된 상태입니다.\]](http://docs.aws.amazon.com/ko_kr/rekognition/latest/dg/images/90face.png)


.jpg 형식의 일부 이미지는 Exif 메타데이터에 방향 정보를 포함합니다. 가능한 경우 이미지의 Exif 메타데이터에는 방향이 포함됩니다. Exif 메타데이터의 `orientation` 필드에서 이미지의 방향을 찾을 수 있습니다. Amazon Rekognition Image는 Exif 메타데이터에서 이미지 방향 정보의 유무를 식별하지만 해당 정보에 대한 액세스를 제공하지 않습니다. 이미지의 Exif 메타데이터에 액세스하려면 타사 라이브러리를 사용하거나 고유한 코드를 작성하십시오. 자세한 내용은 [Exif 버전 2.32](http://cipa.jp/std/documents/download_e.html?DC-008-Translation-2019-E) 단원을 참조하십시오.

 



이미지의 방향을 알면 이미지를 회전하고 올바르게 표시하도록 코드를 작성할 수 있습니다.

## 경계 상자 표시
<a name="images-bounding-boxes"></a>

이미지 속의 얼굴을 분석하는 Amazon Rekognition Image 작업은 얼굴을 둘러싼 경계 상자의 좌표도 반환합니다. 자세한 내용을 알아보려면 [BoundingBox](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_BoundingBox.html)를 참조하세요.

다음 이미지에 표시된 상자와 비슷한 경계 상자를 애플리케이션에서 얼굴 주위에 표시하려면 코드에 경계 상자 좌표를 사용하세요. 작업에서 반환된 경계 상자 좌표는 이미지의 방향을 반영합니다. 이미지를 올바르게 표시하기 위해 회전해야 하는 경우 경계 상자 좌표를 변환해야 할 수 있습니다.



![\[얼굴이 빨간색 사각형으로 강조 표시된 프로필 아이콘입니다.\]](http://docs.aws.amazon.com/ko_kr/rekognition/latest/dg/images/00facebounding.png)




### Exif 메타데이터에 방향 정보가 있는 경우 경계 상자 표시
<a name="images-exif-metadata"></a>

이미지의 방향이 Exif 메타데이터에 포함되어 있는 경우 Amazon Rekognition Image 작업은 다음을 수행합니다.
+ 작업 응답의 방향 수정 필드에 null을 반환하십시오. 이미지를 회전하려면 코드에서 Exif 메타데이터에 제공된 방향을 사용하십시오.
+ 이미 0도로 향한 경계 상자 좌표를 반환하십시오. 경계 상자를 올바른 위치에 표시하려면 반환된 좌표를 사용하십시오. 해당 좌표를 변환할 필요가 없습니다.

## 예제: 이미지 방향 및 이미지의 경계 상자 좌표 가져오기
<a name="images-correcting-image-orientation-java"></a>

다음 예제에서는 AWS SDK를 사용하여 Exif 이미지의 방향 데이터 및 `RecognizeCelebrities` 작업에서 감지된 유명 인사의 경계 상자 좌표를 가져오는 방법을 보여줍니다.

**참고**  
`OrientationCorrection` 필드를 사용한 이미지 방향 추정 지원은 2021년 8월부로 중단되었습니다. API 응답에 포함된 해당 필드에 대해 반환되는 모든 값은 항상 NULL입니다.

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

이 예제는 로컬 파일 시스템에서 이미지를 로드하고 `RecognizeCelebrities` 작업을 직접 호출하고 이미지의 높이와 너비를 결정하며 회전된 이미지에 대한 얼굴의 경계 상자 좌표를 계산합니다. 이 예제에서는 Exif 메타데이터에 저장된 방향 정보를 처리하는 방법을 보여주지 않습니다.

`main` 함수에서, `photo` 값을 로컬에 저장된 이미지(.png 또는 .jpg 형식)의 이름과 경로로 바꾸십시오.

```
//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 java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.List;
import javax.imageio.ImageIO;
import com.amazonaws.services.rekognition.AmazonRekognition;
import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
import com.amazonaws.services.rekognition.model.Image;
import com.amazonaws.services.rekognition.model.RecognizeCelebritiesRequest;
import com.amazonaws.services.rekognition.model.RecognizeCelebritiesResult;
import com.amazonaws.util.IOUtils;
import com.amazonaws.services.rekognition.model.AmazonRekognitionException;
import com.amazonaws.services.rekognition.model.BoundingBox;
import com.amazonaws.services.rekognition.model.Celebrity;
import com.amazonaws.services.rekognition.model.ComparedFace;

public class RotateImage {

public static void main(String[] args) throws Exception {

  String photo = "photo.png";

  //Get Rekognition client
 AmazonRekognition amazonRekognition = AmazonRekognitionClientBuilder.defaultClient();


  // Load image
  ByteBuffer imageBytes=null;
  BufferedImage image = null;

  try (InputStream inputStream = new FileInputStream(new File(photo))) {
     imageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream));

  }
  catch(Exception e)
  {
      System.out.println("Failed to load file " + photo);
      System.exit(1);
  }

  //Get image width and height
  InputStream imageBytesStream;
  imageBytesStream = new ByteArrayInputStream(imageBytes.array());

  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  image=ImageIO.read(imageBytesStream);
  ImageIO.write(image, "jpg", baos);

  int height = image.getHeight();
  int width = image.getWidth();

  System.out.println("Image Information:");
  System.out.println(photo);
  System.out.println("Image Height: " + Integer.toString(height));
  System.out.println("Image Width: " + Integer.toString(width));

  //Call GetCelebrities

  try{
    RecognizeCelebritiesRequest request = new RecognizeCelebritiesRequest()
           .withImage(new Image()
              .withBytes((imageBytes)));


      RecognizeCelebritiesResult result = amazonRekognition.recognizeCelebrities(request);
      // The returned value of OrientationCorrection will always be null
      System.out.println("Orientation: " + result.getOrientationCorrection() + "\n");
      List <Celebrity> celebs = result.getCelebrityFaces();

      for (Celebrity celebrity: celebs) {
          System.out.println("Celebrity recognized: " + celebrity.getName());
          System.out.println("Celebrity ID: " + celebrity.getId());
          ComparedFace  face = celebrity.getFace()
;             ShowBoundingBoxPositions(height,
                  width,
                  face.getBoundingBox(),
                  result.getOrientationCorrection());
                 
            System.out.println();
       }

   } catch (AmazonRekognitionException e) {
      e.printStackTrace();
   }

}


public static void ShowBoundingBoxPositions(int imageHeight, int imageWidth, BoundingBox box, String rotation) {

  float left = 0;
  float top = 0;
   
  if(rotation==null){
      System.out.println("No estimated estimated orientation. Check Exif data.");
      return;
  }
  //Calculate face position based on image orientation.
  switch (rotation) {
     case "ROTATE_0":
        left = imageWidth * box.getLeft();
        top = imageHeight * box.getTop();
        break;
     case "ROTATE_90":
        left = imageHeight * (1 - (box.getTop() + box.getHeight()));
        top = imageWidth * box.getLeft();
        break;
     case "ROTATE_180":
        left = imageWidth - (imageWidth * (box.getLeft() + box.getWidth()));
        top = imageHeight * (1 - (box.getTop() + box.getHeight()));
        break;
     case "ROTATE_270":
        left = imageHeight * box.getTop();
        top = imageWidth * (1 - box.getLeft() - box.getWidth());
        break;
     default:
        System.out.println("No estimated orientation information. Check Exif data.");
        return;
  }

  //Display face location information.
  System.out.println("Left: " + String.valueOf((int) left));
  System.out.println("Top: " + String.valueOf((int) top));
  System.out.println("Face Width: " + String.valueOf((int)(imageWidth * box.getWidth())));
  System.out.println("Face Height: " + String.valueOf((int)(imageHeight * box.getHeight())));

  }
}
```

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

이 예제에서는 PIL/Pillow 이미지 라이브러리를 사용하여 이미지 너비와 높이를 확인합니다. 자세한 내용은 [Pillow](https://pillow.readthedocs.io/en/stable/)를 참조하십시오. 이 예제는 애플리케이션에서 필요할 수 있는 exif 메타데이터를 유지합니다.

`main` 함수에서, `photo` 값을 로컬에 저장된 이미지(.png 또는 .jpg 형식)의 이름과 경로로 바꾸십시오.

```
#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
import io
from PIL import Image


# Calculate positions from from estimated rotation
def show_bounding_box_positions(imageHeight, imageWidth, box):
    left = 0
    top = 0

    print('Left: ' + '{0:.0f}'.format(left))
    print('Top: ' + '{0:.0f}'.format(top))
    print('Face Width: ' + "{0:.0f}".format(imageWidth * box['Width']))
    print('Face Height: ' + "{0:.0f}".format(imageHeight * box['Height']))


def celebrity_image_information(photo):
    client = boto3.client('rekognition')

    # Get image width and height
    image = Image.open(open(photo, 'rb'))
    width, height = image.size

    print('Image information: ')
    print(photo)
    print('Image Height: ' + str(height))
    print('Image Width: ' + str(width))

    # call detect faces and show face age and placement
    # if found, preserve exif info
    stream = io.BytesIO()
    if 'exif' in image.info:
        exif = image.info['exif']
        image.save(stream, format=image.format, exif=exif)
    else:
        image.save(stream, format=image.format)
    image_binary = stream.getvalue()

    response = client.recognize_celebrities(Image={'Bytes': image_binary})

    print()
    print('Detected celebrities for ' + photo)

    for celebrity in response['CelebrityFaces']:
        print('Name: ' + celebrity['Name'])
        print('Id: ' + celebrity['Id'])

        # Value of "orientation correction" will always be null
        if 'OrientationCorrection' in response:
            show_bounding_box_positions(height, width, celebrity['Face']['BoundingBox'])

        print()
    return len(response['CelebrityFaces'])


def main():
    photo = 'photo'

    celebrity_count = celebrity_image_information(photo)
    print("celebrities detected: " + str(celebrity_count))


if __name__ == "__main__":
    main()
```

------
#### [ 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/RotateImage.java)에서 확인하세요.

```
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.RecognizeCelebritiesRequest;
import software.amazon.awssdk.services.rekognition.model.Image;
import software.amazon.awssdk.services.rekognition.model.RecognizeCelebritiesResponse;
import software.amazon.awssdk.services.rekognition.model.Celebrity;
import software.amazon.awssdk.services.rekognition.model.ComparedFace;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;
import software.amazon.awssdk.services.rekognition.model.BoundingBox;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
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 RotateImage {
    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_WEST_2;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        System.out.println("Locating celebrities in " + sourceImage);
        recognizeAllCelebrities(rekClient, sourceImage);
        rekClient.close();
    }

    public static void recognizeAllCelebrities(RekognitionClient rekClient, String sourceImage) {
        try {
            BufferedImage image;
            InputStream sourceStream = new FileInputStream(sourceImage);
            SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream);

            image = ImageIO.read(sourceBytes.asInputStream());
            int height = image.getHeight();
            int width = image.getWidth();

            Image souImage = Image.builder()
                    .bytes(sourceBytes)
                    .build();

            RecognizeCelebritiesRequest request = RecognizeCelebritiesRequest.builder()
                    .image(souImage)
                    .build();

            RecognizeCelebritiesResponse result = rekClient.recognizeCelebrities(request);
            List<Celebrity> celebs = result.celebrityFaces();
            System.out.println(celebs.size() + " celebrity(s) were recognized.\n");
            for (Celebrity celebrity : celebs) {
                System.out.println("Celebrity recognized: " + celebrity.name());
                System.out.println("Celebrity ID: " + celebrity.id());
                ComparedFace face = celebrity.face();
                ShowBoundingBoxPositions(height,
                        width,
                        face.boundingBox(),
                        result.orientationCorrectionAsString());
            }

        } catch (RekognitionException | FileNotFoundException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void ShowBoundingBoxPositions(int imageHeight, int imageWidth, BoundingBox box, String rotation) {
        float left;
        float top;
        if (rotation == null) {
            System.out.println("No estimated estimated orientation.");
            return;
        }

        // Calculate face position based on the image orientation.
        switch (rotation) {
            case "ROTATE_0" -> {
                left = imageWidth * box.left();
                top = imageHeight * box.top();
            }
            case "ROTATE_90" -> {
                left = imageHeight * (1 - (box.top() + box.height()));
                top = imageWidth * box.left();
            }
            case "ROTATE_180" -> {
                left = imageWidth - (imageWidth * (box.left() + box.width()));
                top = imageHeight * (1 - (box.top() + box.height()));
            }
            case "ROTATE_270" -> {
                left = imageHeight * box.top();
                top = imageWidth * (1 - box.left() - box.width());
            }
            default -> {
                System.out.println("No estimated orientation information. Check Exif data.");
                return;
            }
        }

        System.out.println("Left: " + (int) left);
        System.out.println("Top: " + (int) top);
        System.out.println("Face Width: " + (int) (imageWidth * box.width()));
        System.out.println("Face Height: " + (int) (imageHeight * box.height()));
    }
}
```

------