

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

# 사용자 지정 레이블 예
<a name="examples"></a>

이 섹션에는 Amazon Rekognition Custom Labels의 기능을 사용하는 방법을 보여주는 예가 포함되어 있습니다.


| 예제 | 설명 | 
| --- | --- | 
|  [모델 피드백을 사용하여 모델 개선](ex-feedback.md)  |  사람의 검증을 통해 새 훈련 데이터 세트를 생성하여 모델을 개선하는 방법을 보여줍니다.  | 
|  [Amazon Rekognition Custom Labels 데모](ex-custom-labels-demo.md)  |  `DetectCustomLabels`에 대한 직접 호출 결과를 표시하는 사용자 인터페이스 데모  | 
|  [비디오에서 사용자 지정 레이블 감지](ex-video-extraction.md)  |  `DetectCustomLabels`를 비디오에서 추출한 프레임과 함께 사용하는 방법을 보여줍니다.  | 
|  [AWS Lambda 함수를 사용하여 이미지 분석](ex-lambda.md)  |  `DetectCustomLabels`를 Lambda 함수와 함께 사용하는 방법을 보여줍니다.  | 
|  [CSV 파일로 매니페스트 파일 생성](ex-csv-manifest.md)  |  CSV 파일을 사용하여 전체 이미지(분류)와 관련된 [객체, 장면 및 개념](understanding-custom-labels.md#tm-classification)을 찾는 데 적합한 매니페스트 파일을 생성하는 방법을 보여줍니다.  | 

# 모델 피드백을 사용하여 모델 개선
<a name="ex-feedback"></a>

모델 피드백 솔루션을 사용하면 모델 예측에 피드백을 제공하고 사람의 검증을 통해 개선할 수 있습니다. 용례에 따라 이미지 수가 적은 훈련 데이터 세트로도 목적을 달성할 수 있습니다. 더 정확한 모델을 구축하려면 주석이 달린 더 큰 훈련 세트가 필요할 수 있습니다. 모델 피드백 솔루션을 사용하면 모델 지원을 통해 더 큰 데이터 세트를 만들 수 있습니다.

모델 피드백 솔루션을 설치하고 구성하려면 [모델 피드백 솔루션](https://github.com/aws-samples/amazon-rekognition-custom-labels-feedback-solution)을 참조하세요.

모델을 지속적으로 개선하기 위한 워크플로는 다음과 같습니다.

1. 모델의 첫 번째 버전을 학습시키세요(작은 학습 데이터 세트를 사용할 수도 있음).

1. 모델 피드백 솔루션에 주석이 없는 데이터 세트를 제공하세요.

1. 모델 피드백 솔루션은 현재 모델을 사용합니다. 새 데이터 세트에 주석을 달기 위해 사람의 검증 작업을 시작합니다.

1. 모델 피드백 솔루션은 사람의 피드백을 기반으로 새 모델을 생성하는 데 사용할 매니페스트 파일을 생성합니다.

# Amazon Rekognition Custom Labels 데모
<a name="ex-custom-labels-demo"></a>

Amazon Rekognition Custom Labels 데모는 [DetectCustomLabels](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectCustomLabels) API를 사용하여 로컬 컴퓨터의 이미지를 분석하는 사용자 인터페이스를 보여줍니다.

애플리케이션에는 AWS 계정의 Amazon Rekognition Custom Labels 모델에 대한 정보가 표시됩니다. 실행 모델을 선택한 후 로컬 컴퓨터에서 이미지를 분석할 수 있습니다. 필요한 경우 모델을 시작할 수 있습니다. 모델 실행을 중지할 수도 있습니다. 애플리케이션은 Amazon Cognito, Amazon S3, Amazon CloudFront 등과 같은 다른 AWS 서비스와 통합된 것을 보여줍니다.

자세한 내용은 [Amazon Rekognition Custom Labels 데모](https://github.com/aws-samples/amazon-rekognition-custom-labels-demo)를 참조하세요.

# 비디오에서 사용자 지정 레이블 감지
<a name="ex-video-extraction"></a>

다음 예제는 `DetectCustomLabels`와 비디오에서 추출한 프레임을 함께 사용하는 방법을 보여줍니다. 코드는 mov** 및 mp4** 형식의 비디오 파일을 사용하여 테스트되었습니다.

**`DetectCustomLabels`를 캡처한 프레임과 함께 사용**

1. 아직 설치하지 않은 경우 및 AWS SDKs AWS CLI 를 설치하고 구성합니다. 자세한 내용은 [4단계: AWS CLI 및 AWS SDKs 설정](su-awscli-sdk.md) 단원을 참조하십시오.

1. `rekognition:DetectCustomLabels` 및 `AmazonS3ReadOnlyAccess`의 권한이 있는지 확인하세요. 자세한 내용은 [4단계: AWS CLI 및 AWS SDKs 설정](su-awscli-sdk.md) 섹션을 참조하세요.

1. 다음 예제 코드를 사용하세요. `videoFile`의 값을 비디오 파일 이름으로 변경합니다. `projectVersionArn`의 값을 Amazon Rekognition Custom Labels 모델의 Amazon 리소스 이름(ARN)으로 변경합니다.

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   
   """
   Purpose
   Shows how to analyze a local video with an Amazon Rekognition Custom Labels model.
   """
   import argparse
   import logging
   import json
   import math
   import cv2
   import boto3
   
   from botocore.exceptions import ClientError
   
   logger = logging.getLogger(__name__)
   
   
   def analyze_video(rek_client, project_version_arn, video_file):
       """
       Analyzes a local video file with an Amazon Rekognition Custom Labels model.
       Creates a results JSON file based on the name of the supplied video file.
       :param rek_client: A Boto3 Amazon Rekognition client.
       :param project_version_arn: The ARN of the Custom Labels model that you want to use.
       :param video_file: The video file that you want to analyze.
       """
       
       custom_labels = []
       cap = cv2.VideoCapture(video_file)
       frame_rate = cap.get(5)  # Frame rate.
       while cap.isOpened():
           frame_id = cap.get(1)  # Current frame number.
           print(f"Processing frame id: {frame_id}")
           ret, frame = cap.read()
           if ret is not True:
               break
           if frame_id % math.floor(frame_rate) == 0:
               has_frame, image_bytes = cv2.imencode(".jpg", frame)
   
               if has_frame:
                   response = rek_client.detect_custom_labels(
                       Image={
                           'Bytes': image_bytes.tobytes(),
                       },
                       ProjectVersionArn=project_version_arn
                   )
   
               for elabel in response["CustomLabels"]:
                   elabel["Timestamp"] = (frame_id/frame_rate)*1000
                   custom_labels.append(elabel)
   
       print(custom_labels)
   
       with open(video_file + ".json", "w", encoding="utf-8") as f:
           f.write(json.dumps(custom_labels))
   
       cap.release()
   
   
   def add_arguments(parser):
       """
       Adds command line arguments to the parser.
       :param parser: The command line parser.
       """
   
       parser.add_argument(
           "project_version_arn", help="The ARN of the model that you want to use."
       )
   
       parser.add_argument(
           "video_file", help="The local path to the video that you want to analyze."
       )
   
   
   def main():
   
       logging.basicConfig(level=logging.INFO,
                           format="%(levelname)s: %(message)s")
   
       try:
           # Get command line arguments.
           parser = argparse.ArgumentParser(usage=argparse.SUPPRESS)
           add_arguments(parser)
           args = parser.parse_args()
   
           session = boto3.Session(profile_name='custom-labels-access')
           rekognition_client = session.client("rekognition")
   
           analyze_video(rekognition_client,
                        args.project_version_arn, args.video_file)
   
       except ClientError as err:
           print(f"Couldn't analyze video: {err}")
   
   
   if __name__ == "__main__":
       main()
   ```

# AWS Lambda 함수를 사용하여 이미지 분석
<a name="ex-lambda"></a>

AWS Lambda 는 서버를 프로비저닝하거나 관리하지 않고도 코드를 실행할 수 있는 컴퓨팅 서비스입니다. 예를 들어, 애플리케이션 코드를 호스팅할 서버를 생성할 필요 없이 모바일 애플리케이션에서 제출된 이미지를 분석할 수 있습니다. 다음 지침은 [DetectCustomLabels](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectCustomLabels)를 직접 호출하는 Lambda 함수를 Python에서 생성하는 방법을 보여줍니다. 함수는 제공된 이미지를 분석하고 이미지에서 찾은 레이블 목록을 반환합니다. 지침에는 Amazon S3 버킷의 이미지 또는 로컬 컴퓨터에서 제공된 이미지를 사용하여 Lambda 함수를 직접 호출하는 방법을 보여주는 예제 Python 코드가 포함되어 있습니다.

**Topics**
+ [

## 1단계: AWS Lambda 함수 생성(콘솔)
](#example-lambda-create-function)
+ [

## 2단계: (선택 사항) 계층 생성 (콘솔)
](#example-lambda-create-layer)
+ [

## 3단계: Python 코드 추가 (콘솔)
](#example-lambda-add-code)
+ [

## 4단계: Lambda 함수 테스트
](#example-lambda-test)

## 1단계: AWS Lambda 함수 생성(콘솔)
<a name="example-lambda-create-function"></a>

이 단계에서는 AWS 함수가 `DetectCustomLabels` 작업을 호출할 수 있도록 빈 함수와 IAM 실행 역할을 생성합니다. 또한 분석용 이미지를 저장하는 Amazon S3 버킷에 대한 액세스 권한도 부여합니다. 그리고 다음에 대한 환경 변수를 지정합니다.
+ Lambda 함수에서 사용하려는 Amazon Rekognition Custom Labels 모델
+ 모델에 사용하려는 신뢰 한도

나중에 Lambda 함수에 소스 코드와 계층(선택 사항)을 추가합니다.

**AWS Lambda 함수를 생성하려면(콘솔)**

1. 에 로그인 AWS Management Console 하고 [https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/) AWS Lambda 콘솔을 엽니다.

1. **함수 생성**을 선택합니다. 자세한 내용은 [콘솔로 Lambda 함수 생성](https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html)을 참조하세요.

1. 다음과 같은 옵션을 선택하세요.
   + **새로 작성**을 선택합니다.
   + **함수 이름**의 값을 입력합니다.
   + **런타임**에는 **Python 3.10**을 선택합니다.

1. **함수 생성**을 선택하여 AWS Lambda 함수를 생성합니다.

1. 함수 페이지에서 **구성** 탭을 선택합니다.

1. **환경 변수** 창에서 **편집**을 선택합니다.

1. 다음 환경 변수를 추가합니다. 각 변수에 대해 **환경 변수 추가**를 선택한 다음 변수 키와 값을 입력합니다.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/rekognition/latest/customlabels-dg/ex-lambda.html)

1. **저장**을 선택하여 환경 변수를 저장합니다.

1. **권한** 창의 **실행 역할**에서 IAM 콘솔의 역할을 열 실행 역할을 선택합니다.

1. **권한** 탭에서 **권한 추가**, 그다음 **인라인 정책 생성**을 선택합니다.

1. **JSON**을 선택하고 기존 정책을 다음 정책으로 바꿉니다.

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Action": "rekognition:DetectCustomLabels",
               "Resource": "*",
               "Effect": "Allow",
               "Sid": "DetectCustomLabels"
           }
       ]
   }
   ```

------

1. **다음**을 선택합니다.

1. **정책 세부 정보**에 DetectCustomLabels-Access**와 같은 정책의 이름을 입력합니다.

1. **정책 생성**을 선택합니다.

1. Amazon S3 버킷에 분석용 이미지를 저장하는 경우 10\$114단계를 반복합니다.

   1. 11단계에서는 다음 정책을 사용하십시오. *버킷/폴더 경로*를 Amazon S3 버킷 및 분석하려는 이미지의 폴더 경로로 바꿉니다.

------
#### [ JSON ]

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Sid": "S3Access",
                  "Effect": "Allow",
                  "Action": "s3:GetObject",
                  "Resource": "arn:aws:s3:::bucket/folder path/*"
              }
          ]
      }
      ```

------

   1. 13단계에서는 *S3Bucket-access*와 같은 다른 정책 이름을 선택합니다.

## 2단계: (선택 사항) 계층 생성 (콘솔)
<a name="example-lambda-create-layer"></a>

이 단계는 예제를 실행하는 데 필수 사항이 아닙니다. `DetectCustomLabels` 작업은 AWS SDK for Python(Boto3)의 일부로 기본 Lambda Python 환경에 포함됩니다. Lambda 함수의 다른 부분에서 기본 Lambda Python 환경에 없는 최신 AWS 서비스 업데이트가 필요한 경우이 단계를 수행하여 최신 Boto3 SDK 릴리스를 함수에 계층으로 추가합니다.

먼저 Boto3 SDK가 포함된 .zip 파일 아카이브를 생성합니다. 그런 다음 계층을 생성하고 .zip 파일 아카이브를 계층에 추가합니다. 자세한 내용은 [Lambda 함수에서 계층 사용](https://docs.aws.amazon.com/lambda/latest/dg/invocation-layers.html#invocation-layers-using)을 참조하세요.

**계층을 생성하고 추가하려면(콘솔)**

1. 명령 프롬프트를 열고 다음 명령을 입력합니다.

   ```
   pip install boto3 --target python/.
   zip boto3-layer.zip -r python/
   ```

1. zip 파일(boto3-layer.zip)의 이름을 기록해 두세요. 이 절차의 6단계에서 필요합니다.

1. [https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/) AWS Lambda 콘솔을 엽니다.

1. 탐색 창에서 **계층**을 선택합니다.

1. **계층 생성**을 선택합니다.

1. **Name**(이름)과 **Description**(설명)을 입력합니다.

1. **.zip 파일 업로드**를 선택한 후 **업로드**를 선택합니다.

1. 대화 상자에서 이 절차의 1단계에서 만든.zip 파일 아카이브 (boto3-layer.zip)를 선택합니다.

1. 호환되는 런타임은 **Python 3.9**를 선택하세요.

1. **생성**을 선택하여 계층을 생성합니다.

1. 탐색 창 메뉴 아이콘을 선택합니다.

1. 탐색 창에서 **함수**를 선택합니다.

1. 리소스 목록에서 [1단계: AWS Lambda 함수 생성(콘솔)](#example-lambda-create-function) 항목에서 생성한 함수를 선택합니다.

1. **코드** 탭을 선택합니다.

1. **계층** 영역에서 **계층 추가**를 선택합니다.

1. **사용자 지정 계층**을 선택합니다.

1. **사용자 지정 계층**에서 6단계에서 입력한 계층 이름을 선택합니다.

1. **버전**에서 계층 버전을 선택합니다. 계층 버전은 1이어야 합니다.

1. **추가**를 선택합니다.

## 3단계: Python 코드 추가 (콘솔)
<a name="example-lambda-add-code"></a>

이 단계에서는 Lambda 콘솔 코드 편집기를 사용하여 Lambda 함수에 Python 코드를 추가합니다. 해당 코드는 `DetectCustomLabels`로 제공된 이미지를 분석하고 이미지에서 찾은 레이블 목록을 반환합니다. 제공된 이미지는 Amazon S3 버킷에 있거나 byte64로 인코딩된 이미지 바이트로 제공될 수 있습니다.

**Python 코드를 추가하려면 (콘솔)**

1. Lambda 콘솔을 사용하지 않는 경우 다음을 수행합니다.

   1. [https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/) AWS Lambda 콘솔을 엽니다.

   1. [1단계: AWS Lambda 함수 생성(콘솔)](#example-lambda-create-function)에서 생성한 Lambda 함수를 엽니다.

1. **코드** 탭을 선택합니다.

1. **코드 소스**에서 **lambda\$1function.py**의 코드를 다음과 같이 바꾸세요.

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   
   """
   Purpose
   An AWS lambda function that analyzes images with an the Amazon Rekognition
   Custom Labels model.
   """
   import json
   import base64
   from os import environ
   import logging
   import boto3
   
   from botocore.exceptions import ClientError
   
   # Set up logging.
   logger = logging.getLogger(__name__)
   
   # Get the model ARN and confidence.
   model_arn = environ['MODEL_ARN']
   min_confidence = int(environ.get('CONFIDENCE', 50))
   
   # Get the boto3 client.
   rek_client = boto3.client('rekognition')
   
   
   def lambda_handler(event, context):
       """
       Lambda handler function
       param: event: The event object for the Lambda function.
       param: context: The context object for the lambda function.
       return: The labels found in the image passed in the event
       object.
       """
   
       try:
   
           # Determine image source.
           if 'image' in event:
               # Decode the image
               image_bytes = event['image'].encode('utf-8')
               img_b64decoded = base64.b64decode(image_bytes)
               image = {'Bytes': img_b64decoded}
   
   
           elif 'S3Object' in event:
               image = {'S3Object':
                        {'Bucket':  event['S3Object']['Bucket'],
                         'Name': event['S3Object']['Name']}
                        }
   
           else:
               raise ValueError(
                   'Invalid source. Only image base 64 encoded image bytes or S3Object are supported.')
   
   
           # Analyze the image.
           response = rek_client.detect_custom_labels(Image=image,
               MinConfidence=min_confidence,
               ProjectVersionArn=model_arn)
   
           # Get the custom labels
           labels = response['CustomLabels']
   
           lambda_response = {
               "statusCode": 200,
               "body": json.dumps(labels)
           }
   
       except ClientError as err:
           error_message = f"Couldn't analyze image. " + \
               err.response['Error']['Message']
   
           lambda_response = {
               'statusCode': 400,
               'body': {
                   "Error": err.response['Error']['Code'],
                   "ErrorMessage": error_message
               }
           }
           logger.error("Error function %s: %s",
               context.invoked_function_arn, error_message)
   
       except ValueError as val_error:
           lambda_response = {
               'statusCode': 400,
               'body': {
                   "Error": "ValueError",
                   "ErrorMessage": format(val_error)
               }
           }
           logger.error("Error function %s: %s",
               context.invoked_function_arn, format(val_error))
   
       return lambda_response
   ```

1. Lambda 함수를 배포하려면 **배포**를 선택합니다.

## 4단계: Lambda 함수 테스트
<a name="example-lambda-test"></a>

이 단계에서는 컴퓨터의 Python 코드를 사용하여 로컬 이미지 또는 Amazon S3 버킷의 이미지를 Lambda 함수에 전달합니다. 로컬 컴퓨터에서 전달된 이미지는 6291456바이트보다 작아야 합니다. 이미지가 더 크면 Amazon S3 버킷에 이미지를 업로드하고 이미지에 대한 Amazon S3 경로를 사용하여 스크립트를 호출합니다. Amazon S3 버킷에 이미지 파일을 업로드하는 방법에 대한 자세한 내용은 [객체 업로드](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html)를 참조하세요.

Lambda 함수를 생성한 리전과 동일한 AWS 리전에서 코드를 실행해야 합니다. Lambda [콘솔의 함수 세부 정보 페이지의 탐색 모음에서 Lambda](https://console.aws.amazon.com/lambda/) 함수의 AWS 리전을 볼 수 있습니다.

 AWS Lambda 함수가 제한 시간 오류를 반환하는 경우 Lambda 함수의 제한 시간을 연장합니다. 자세한 내용은 [함수 제한 시간 구성(콘솔)을](https://docs.aws.amazon.com/lambda/latest/dg/configuration-function-common.html#configuration-timeout-console) 참조하세요.

코드에서 Lambda 함수를 호출하는 방법에 대한 자세한 내용은 [AWS Lambda 함수 호출을 참조하세요](https://docs.aws.amazon.com/lambda/latest/dg/invoking-lambda-functions.html).

**Lambda 함수를 테스트하는 방법**

1. `lambda:InvokeFunction` 권한이 있는지 확인합니다. 다음 정책을 사용할 수 있습니다.

   [Lambda 콘솔](https://console.aws.amazon.com/lambda/)의 함수 개요에서 Lambda 함수 함수에 대한 ARN을 가져올 수 있습니다.

   액세스 권한을 제공하려면 사용자, 그룹 또는 역할에 권한을 추가하세요.
   + 의 사용자 및 그룹 AWS IAM Identity Center:

     권한 세트를 생성합니다. *AWS IAM Identity Center 사용자 안내서*에서 [권한 세트 생성](https://docs.aws.amazon.com//singlesignon/latest/userguide/howtocreatepermissionset.html)의 지침을 따릅니다.
   + ID 제공업체를 통해 IAM에서 관리되는 사용자:

     ID 페더레이션을 위한 역할을 생성합니다. *IAM 사용자 설명서*의 [Create a role for a third-party identity provider (federation)](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_roles_create_for-idp.html)의 지침을 따릅니다.
   + IAM 사용자:
     + 사용자가 맡을 수 있는 역할을 생성합니다. *IAM 사용자 설명서*에서 [Create a role for an IAM user](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_roles_create_for-user.html)의 지침을 따릅니다.
     + (권장되지 않음) 정책을 사용자에게 직접 연결하거나 사용자를 사용자 그룹에 추가합니다. *IAM 사용 설명서*에서 [사용자(콘솔)에 권한 추가](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_users_change-permissions.html#users_change_permissions-add-console)의 지침을 따릅니다.

1.  AWS SDK for Python을 설치하고 구성합니다. 자세한 내용은 [4단계: AWS CLI 및 AWS SDKs 설정](su-awscli-sdk.md) 단원을 참조하십시오.

1. [1단계: AWS Lambda 함수 생성(콘솔)](#example-lambda-create-function)의 7단계에서 지정한 [모델을 시작](rm-start.md)합니다.

1. 다음 코드를 `client.py` 이름의 파일에 저장합니다.

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   
   """
   Purpose
   Test code for running the Amazon Rekognition Custom Labels Lambda
   function example code.
   """
   
   import argparse
   import logging
   import base64
   import json
   import boto3
   
   from botocore.exceptions import ClientError
   
   
   logger = logging.getLogger(__name__)
   
   
   def analyze_image(function_name, image):
       """Analyzes an image with an AWS Lambda function.
       :param image: The image that you want to analyze.
       :return The status and classification result for
       the image analysis.
       """
   
       lambda_client = boto3.client('lambda')
   
       lambda_payload = {}
   
       if image.startswith('s3://'):
           logger.info("Analyzing image from S3 bucket: %s", image)
           bucket, key = image.replace("s3://", "").split("/", 1)
           s3_object = {
               'Bucket': bucket,
               'Name': key
           }
           lambda_payload = {"S3Object": s3_object}
   
       # Call the lambda function with the image.
       else:
           with open(image, 'rb') as image_file:
               logger.info("Analyzing local image image: %s ", image)
               image_bytes = image_file.read()
               data = base64.b64encode(image_bytes).decode("utf8")
   
               lambda_payload = {"image": data}
   
       response = lambda_client.invoke(FunctionName=function_name,
                                       Payload=json.dumps(lambda_payload))
   
       return json.loads(response['Payload'].read().decode())
   
   
   def add_arguments(parser):
       """
       Adds command line arguments to the parser.
       :param parser: The command line parser.
       """
   
       parser.add_argument(
           "function", help="The name of the AWS Lambda function that you want " \
           "to use to analyze the image.")
       parser.add_argument(
           "image", help="The local image that you want to analyze.")
   
   
   def main():
       """
       Entrypoint for script.
       """
       try:
           logging.basicConfig(level=logging.INFO,
                               format="%(levelname)s: %(message)s")
   
           # Get command line arguments.
           parser = argparse.ArgumentParser(usage=argparse.SUPPRESS)
           add_arguments(parser)
           args = parser.parse_args()
   
           # Get analysis results.
           result = analyze_image(args.function, args.image)
           status = result['statusCode']
   
           if status == 200:
               labels = result['body']
               labels = json.loads(labels)
               print(f"There are {len(labels)} labels in the image.")
               for custom_label in labels:
                   confidence = int(round(custom_label['Confidence'], 0))
                   print(
                       f"Label: {custom_label['Name']}: Confidence: {confidence}%")
           else:
               print(f"Error: {result['statusCode']}")
               print(f"Message: {result['body']}")
   
       except ClientError as error:
           logging.error(error)
           print(error)
   
   
   if __name__ == "__main__":
       main()
   ```

1. 코드를 실행합니다. 명령줄 인수에 Lambda 함수 이름과 분석하려는 이미지를 제공하세요. 로컬 이미지에 대한 경로 또는 Amazon S3 버킷에 저장된 이미지에 대한 S3 경로를 제공할 수 있습니다. 예제:

   ```
   python client.py function_name s3://bucket/path/image.jpg
   ```

   이미지가 Amazon S3 버킷에 있는 경우, [1단계: AWS Lambda 함수 생성(콘솔)](#example-lambda-create-function)의 15단계에서 지정한 것과 동일한 버킷인지 확인하세요.

   성공하면 이미지에서 찾은 레이블 목록이 출력됩니다. 레이블이 반환되지 않는 경우 [1단계: AWS Lambda 함수 생성(콘솔)](#example-lambda-create-function)의 7단계에서 설정한 신뢰도 값을 낮추는 것이 좋습니다.

1. Lambda 함수 사용을 마쳤지만 다른 애플리케이션에서 해당 모델을 사용하지 않는 경우 [모델을 중지](rm-stop.md)하세요. 다음에 Lambda 함수를 사용하려는 경우 [모델을 시작해야](rm-start.md) 한다는 점을 기억하십시오.