

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 检测不当图像
<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 SDK。有关更多信息，请参阅 [第 2 步：设置 AWS CLI and AWS 软件开发工具包](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`的值替换为您的开发人员资料的名称。要使用适配器，请为`project-version`参数提供项目版本的 ARN。

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

   如果您在 Windows 设备上访问 CLI，请使用双引号代替单引号，并用反斜杠（即 \\）对内部双引号进行转义，以解决可能遇到的任何解析器错误。例如，请参阅以下内容：

   ```
   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 响应中，注意以下几点：
+ **不当图像检测信息** – 该示例显示了图像中发现的不当或冒犯性内容的标签列表。此列表包括在图像中检测到的顶级标签和所有第二级标签。

  **标签** – 每个标签具有一个名称、Amazon Rekognition 估计的置信度（用于指示标签的准确性）以及其父标签的名称。顶级标签的父名称为 `""`。

  **标签置信度** – 每个标签均有一个介于 0 和 100 之间的置信度值，该值指示 Amazon Rekognition 具有的百分比置信度（用于指示标签的准确性）。您可以在 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"
        }
    ]
}
```