

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

# 부적절한 이미지 감지
<a name="procedure-moderate-images"></a>

[DetectModerationLabels](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectModerationLabels.html) 작업을 사용하여 이미지에 부적절하거나 불쾌감을 주는 콘텐츠가 포함되어 있는지 확인할 수 있습니다. Amazon Rekognition의 조절 레이블 목록은 [이미지 및 비디오 조절 API 사용](https://docs.aws.amazon.com/rekognition/latest/dg/moderation.html#moderation-api)을 참조하세요.



## 이미지에서 부적절한 콘텐츠 감지
<a name="moderate-images-sdk"></a>

이미지는 .jpg 또는 .png 형식이어야 합니다. 입력 이미지를 이미지 바이트 배열(base64 인코딩 이미지 바이트)로 제공하거나 Amazon S3 객체를 지정할 수 있습니다. 이 절차에서는 이미지(.jpg 또는 .png)를 S3 버킷에 업로드합니다.

이러한 절차를 실행하려면 AWS CLI 또는 적절한 AWS SDK가 설치되어 있어야 합니다. 자세한 내용은 [Amazon Rekognition 시작](getting-started.md) 단원을 참조하십시오. 사용할 AWS 계정은 Amazon Rekognition API에 대한 액세스 권한을 가지고 있어야 합니다. 자세한 내용은 [Amazon Rekognition에서 정의한 작업](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonrekognition.html#amazonrekognition-actions-as-permissions)을 참조하세요.

**이미지에서 조정 레이블(SDK)을 감지하려면**

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. S3 버킷에 이미지를 업로드합니다.

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

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

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

   이 예제는 감지된 부적절한 콘텐츠의 레이블 이름, 신뢰도 수준 및 감지된 조절 레이블의 상위 레이블을 출력합니다.

   `amzn-s3-demo-bucket` 및 `photo` 값을 2단계에서 사용한 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 aws.example.rekognition.image;
   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.DetectModerationLabelsRequest;
   import com.amazonaws.services.rekognition.model.DetectModerationLabelsResult;
   import com.amazonaws.services.rekognition.model.Image;
   import com.amazonaws.services.rekognition.model.ModerationLabel;
   import com.amazonaws.services.rekognition.model.S3Object;
   
   import java.util.List;
   
   public class DetectModerationLabels
   {
      public static void main(String[] args) throws Exception
      {
         String photo = "input.jpg";
         String bucket = "bucket";
         
         AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
         
         DetectModerationLabelsRequest request = new DetectModerationLabelsRequest()
           .withImage(new Image().withS3Object(new S3Object().withName(photo).withBucket(bucket)))
           .withMinConfidence(60F);
         try
         {
              DetectModerationLabelsResult result = rekognitionClient.detectModerationLabels(request);
              List<ModerationLabel> labels = result.getModerationLabels();
              System.out.println("Detected labels for " + photo);
              for (ModerationLabel label : labels)
              {
                 System.out.println("Label: " + label.getName()
                  + "\n Confidence: " + label.getConfidence().toString() + "%"
                  + "\n Parent:" + label.getParentName());
             }
          }
          catch (AmazonRekognitionException e)
          {
            e.printStackTrace();
          }
       }
   }
   ```

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

   ```
   //snippet-start:[rekognition.java2.recognize_video_text.import]
   //snippet-start:[rekognition.java2.detect_mod_labels.import]
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   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.RekognitionException;
   import software.amazon.awssdk.services.rekognition.model.Image;
   import software.amazon.awssdk.services.rekognition.model.DetectModerationLabelsRequest;
   import software.amazon.awssdk.services.rekognition.model.DetectModerationLabelsResponse;
   import software.amazon.awssdk.services.rekognition.model.ModerationLabel;
   import java.io.FileInputStream;
   import java.io.FileNotFoundException;
   import java.io.InputStream;
   import java.util.List;
   //snippet-end:[rekognition.java2.detect_mod_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 ModerateLabels {
   
    public static void main(String[] args) {
   
        final String usage = "\n" +
            "Usage: " +
            "   <sourceImage>\n\n" +
            "Where:\n" +
            "   sourceImage - The path to the image (for example, C:\\AWS\\pic1.png). \n\n";
   
        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)
            .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
            .build();
   
        detectModLabels(rekClient, sourceImage);
        rekClient.close();
    }
   
    // snippet-start:[rekognition.java2.detect_mod_labels.main]
    public static void detectModLabels(RekognitionClient rekClient, String sourceImage) {
   
        try {
            InputStream sourceStream = new FileInputStream(sourceImage);
            SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream);
            Image souImage = Image.builder()
                .bytes(sourceBytes)
                .build();
   
            DetectModerationLabelsRequest moderationLabelsRequest = DetectModerationLabelsRequest.builder()
                .image(souImage)
                .minConfidence(60F)
                .build();
   
            DetectModerationLabelsResponse moderationLabelsResponse = rekClient.detectModerationLabels(moderationLabelsRequest);
            List<ModerationLabel> labels = moderationLabelsResponse.moderationLabels();
            System.out.println("Detected labels for image");
   
            for (ModerationLabel label : labels) {
                System.out.println("Label: " + label.name()
                    + "\n Confidence: " + label.confidence().toString() + "%"
                    + "\n Parent:" + label.parentName());
            }
   
        } catch (RekognitionException | FileNotFoundException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
    // snippet-end:[rekognition.java2.detect_mod_labels.main]
   ```

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

   이 AWS CLI 명령은 `detect-moderation-labels` CLI 작업에 대한 JSON 출력을 표시합니다.

   `amzn-s3-demo-bucket` 및 `input.jpg`을 2단계에서 사용한 S3 버킷 이름과 이미지 파일 이름으로 바꿉니다. `profile_name`의 값을 개발자 프로필 이름으로 바꿉니다. 어댑터를 사용하려면 프로젝트 버전의 ARN을 `project-version` 파라미터에 제공하세요.

   ```
   aws rekognition detect-moderation-labels --image "{S3Object:{Bucket:<amzn-s3-demo-bucket>,Name:<image-name>}}" \ 
   --profile profile-name \
   --project-version "ARN"
   ```

   Windows 디바이스에서 CLI에 액세스하는 경우 작은따옴표 대신 큰따옴표를 사용하고 내부 큰따옴표는 백슬래시(즉 \$1)로 이스케이프 처리하여 발생할 수 있는 구문 분석 오류를 해결합니다. 예를 들어 다음을 참조하세요.

   ```
   aws rekognition detect-moderation-labels --image "{\"S3Object\":{\"Bucket\":\"amzn-s3-demo-bucket\",\"Name\":\"image-name\"}}" \
   --profile profile-name
   ```

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

   이 예제는 감지된 부적절하거나 불쾌감을 주는 콘텐츠의 레이블 이름, 신뢰도 수준 및 감지된 부적절한 콘텐츠 레이블의 상위 레이블을 출력합니다.

   `main` 함수에서, `amzn-s3-demo-bucket` 및 `photo` 값을 2단계에서 사용한 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 moderate_image(photo, bucket):
       
       session = boto3.Session(profile_name='profile-name')
       client = session.client('rekognition')
   
       response = client.detect_moderation_labels(Image={'S3Object':{'Bucket':bucket,'Name':photo}})
   
       print('Detected labels for ' + photo)
       for label in response['ModerationLabels']:
           print (label['Name'] + ' : ' + str(label['Confidence']))
           print (label['ParentName'])
       return len(response['ModerationLabels'])
   
   def main():
   
       photo='image-name'
       bucket='amzn-s3-demo-bucket'
       label_count=moderate_image(photo, bucket)
       print("Labels detected: " + str(label_count))
   
   if __name__ == "__main__":
       main()
   ```

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

   이 예제는 감지된 부적절하거나 불쾌감을 주는 콘텐츠의 레이블 이름, 신뢰도 수준 및 감지된 조절 레이블의 상위 레이블을 출력합니다.

   `amzn-s3-demo-bucket` 및 `photo` 값을 2단계에서 사용한 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 DetectModerationLabels
   {
       public static void Example()
       {
           String photo = "input.jpg";
           String bucket = "amzn-s3-demo-bucket";
   
           AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();
   
           DetectModerationLabelsRequest detectModerationLabelsRequest = new DetectModerationLabelsRequest()
           {
               Image = new Image()
               {
                   S3Object = new S3Object()
                   {
                       Name = photo,
                       Bucket = bucket
                   },
               },
               MinConfidence = 60F
           };
   
           try
           {
               DetectModerationLabelsResponse detectModerationLabelsResponse = rekognitionClient.DetectModerationLabels(detectModerationLabelsRequest);
               Console.WriteLine("Detected labels for " + photo);
               foreach (ModerationLabel label in detectModerationLabelsResponse.ModerationLabels)
                   Console.WriteLine("Label: {0}\n Confidence: {1}\n Parent: {2}", 
                       label.Name, label.Confidence, label.ParentName);
           }
           catch (Exception e)
           {
               Console.WriteLine(e.Message);
           }
       }
   }
   ```

------

## DetectModerationLabels 작업 요청
<a name="detectmoderation-labels-operation-request"></a>

`DetectModerationLabels`에 대한 입력은 이미지입니다. 이 예제 JSON 입력에서는 Amazon S3 버킷에서 소스 이미지를 불러옵니다. `MinConfidence`는 Amazon Rekognition Image가 응답에 반환하기 위해 충족해야 할 감지된 레이블의 최소 정확성 신뢰도 수준입니다.

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

## DetectModerationLabels 작업 응답
<a name="detectmoderationlabels-operation-response"></a>

 `DetectModerationLabels`가 S3 버킷의 입력 이미지를 감지하거나, 이미지를 이미지 바이트로 직접 제공할 수 있습니다. 다음 예제는 `DetectModerationLabels` 호출로부터의 응답입니다.

다음 JSON 응답 예제에서 다음에 유의하십시오.
+ **부적절한 이미지 감지 정보** - 이 예제에서는 이미지에서 발견된 부적절하거나 불쾌감을 주는 콘텐츠의 레이블 목록을 보여줍니다. 이 목록에는 이미지에서 감지되는 최상위 레이블과 각각의 2수준 레이블이 포함됩니다.

  **레이블** – 각 레이블에는 이름, 해당 레이블이 정확한지에 대한 Amazon Rekognition의 신뢰도 추정, 상위 레이블의 이름이 있습니다. 최상위 레이블의 상위 이름은 `""`입니다.

  **레이블 신뢰도** – 각 레이블에는 레이블이 올바른지에 대해 Amazon Rekognition이 가지고 있는 백분율 신뢰도를 나타내는 0에서 100 사이의 신뢰도 값이 있습니다. API 작업 요청에서 응답으로 반환될 레이블에 필요한 신뢰도 수준을 지정합니다.

```
{
    "ModerationLabels": [
        {
            "Confidence": 99.44782257080078,
            "Name": "Smoking",
            "ParentName": "Drugs & Tobacco Paraphernalia & Use",
            "TaxonomyLevel": 3
        },
        {
            "Confidence": 99.44782257080078,
            "Name": "Drugs & Tobacco Paraphernalia & Use",
            "ParentName": "Drugs & Tobacco",
            "TaxonomyLevel": 2
        },
        {
            "Confidence": 99.44782257080078,
            "Name": "Drugs & Tobacco",
            "ParentName": "",
            "TaxonomyLevel": 1
        }
    ],
    "ModerationModelVersion": "7.0",
    "ContentTypes": [
        {
            "Confidence": 99.9999008178711,
            "Name": "Illustrated"
        }
    ]
}
```