

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# 個人用保護具を検出する。
<a name="ppe-detection"></a>

Amazon Rekognition は、画像内の人物が身につけている個人用保護具(PPE)を検出することができます。この情報を使用して、職場の安全対策を改善することができます。例えば、建設現場で作業員がヘッドカバーを装着しているかどうか、医療従事者がフェイスカバーとハンドカバーを装着しているかどうかを判断するために、PPE 検出を使用することができます。次のイメージは、検出可能な PPE の種類を示したものです。

![\[ヘルメット、安全眼鏡、保護マスク、手袋などの個人用保護具 (PPE) を着用し、電動工具を操作している作業員。アイテムの周りに境界ボックスが表示されている。\]](http://docs.aws.amazon.com/ja_jp/rekognition/latest/dg/images/worker-with-bb.png)


イメージ内の PPE を検出するには、[DetectProtectiveEquipment](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectProtectiveEquipment.html) API を呼び出して、入力イメージを渡します。レスポンスは JSON 構造で、以下が含まれています。
+ 画像内で検出された人物です。
+ PPE を装着している身体の部位 (顔、頭、左手、右手)
+ 身体部位で検出された PPE の種類（フェイスカバー、ハンドカバー、ヘッドカバー）です。
+ 検出された PPE のアイテムについて、PPE が対応する身体部位をカバーしているかどうかを示すインジケータです。

画像内で検出された PPE の人物およびアイテムの位置に対してバウンディングボックスが返されます。

オプションで、画像内で検出された PPE アイテムと人物の概要をリクエストできます。詳細については、「[イメージ内で検出された PPE の概要です。](#ppe-summarization)」を参照してください。

**注記**  
Amazon Rekognition PPE 検出は、顔認識や顔比較を行わないため、検出された人物を特定することはできません。

## PPE の種類です。
<a name="ppe-types"></a>

[DetectProtectiveEquipment](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectProtectiveEquipment.html) は、以下のタイプの PPE を検出します。イメージ内の他のタイプの PPE を検出する場合は、Amazon Rekognition カスタムラベルを使用して、カスタムモデルをトレーニングすることを検討してください。詳細については、「[Amazon Rekognition カスタムラベル](https://docs.aws.amazon.com/rekognition/latest/customlabels-dg/what-is.html)」を参照してください。

### フェイスカバー
<a name="ppe-face-cover"></a>

`DetectProtectiveEquipment` は、外科、N95、布製のマスクなどの一般的な顔カバーを検出できます。

### ハンドカバー
<a name="ppe-hand-cover"></a>

`DetectProtectiveEquipment` 手術用手袋や安全手袋などのハンドカバーを検出できます。

### ヘッドカバー
<a name="ppe-head-cover"></a>

`DetectProtectiveEquipment` 硬い帽子やヘルメットを検出できます。

API は、頭部、手、または顔のカバーが画像内で検出されたことを示します。API は、特定のカバーのタイプに関する情報を返しません。たとえば、ハンドカバーのタイプの「手術用手袋」などです。

## PPE 検出の信頼度
<a name="ppe-confidence"></a>

Amazon Rekognition は、画像内の PPE、人、身体部位の存在について予測を行います。API は Amazon Rekognition が、予測の精度にどの程度自信を持っているかを示すスコア（50-100）を提供します。

**注記**  
個人の権利、プライバシー、サービスへのアクセスに影響を与える決定を行うために `DetectProtectiveEquipment` の操作を使用する予定がある場合は、アクションを起こす前にレビューと検証のために人間に結果を渡すことをお勧めします。

## イメージ内で検出された PPE の概要です。
<a name="ppe-summarization"></a>

オプションで、画像内で検出された PPE アイテムと人物の概要をリクエストすることができます。必要な保護具 (フェイスカバー、ハンドカバー、またはヘッドカバー) のリストと最小信頼度 (80% など) を指定できます。応答には、必要な PPE を持つ人、必要な PPE を持たない人、および決定ができない人物の統合イメージごとの識別子 (ID) 要約が含まれます。

このサマリーでは、「*何人がフェイスカバーを装着していないか*」や「*全員がPPEを装着しているか*」といった質問に素早く答えることができます。概要内で検出された各ユーザーには、一意の ID があります。IDを使用して、PPE を着用していない人のバウンディングボックスの位置などの情報を見つけることができます。

**注記**  
ID は、画像解析ごとにランダムに生成され、画像間や同じ画像の複数の解析で一貫性はありません。

フェイスカバー、ヘッドカバー、ハンドカバー、またはお好みの組み合わせをまとめることができます。必要なタイプの PPE を指定するには、「[要約の要件を指定する](ppe-request-response.md#ppe-summarization-input-parameters)」を参照してください。また、サマリーに含まれる検出のために満たす必要のある最小信頼水準（50～100）を指定することができます。

 `DetectProtectiveEquipment` の要約レスポンスの詳細については、「[保護装置の検出レスポンスの概要](ppe-request-response.md#detect-protective-equipment-response)」を参照してください。

## チュートリアル: PPE でイメージを検出する AWS Lambda 関数の作成
<a name="ppe-tutorial-lambda"></a>

Amazon S3 バケットにあるイメージ内の個人用保護具 (PPE) を検出する AWS Lambda 関数を作成できます。この Java V2 チュートリアルは、「[AWS ドキュメント SDK の例の GitHub リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javav2/usecases/creating_lambda_ppe)」を参照してください。

# 個人用保護具検出 API を理解する
<a name="ppe-request-response"></a>

以下の情報は [DetectProtectiveEquipment](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectProtectiveEquipment.html) API について説明しています。サンプルコードについては、「[画像から個人用保護具を検出します。](ppe-procedure-image.md)」を参照してください。

## 画像を供給する
<a name="detect-protective-equipment-request"></a>

入力画像（JPG または PNG 形式）は、画像バイトとして提供するか、Amazon S3 バケットに保存されている画像を参照することができます。

人物の顔がカメラの方を向いている画像を使用することを推奨します。

入力画像が 0 度回転しない場合は、`DetectProtectiveEquipment` に送信する前に 0 度回転することをお勧めします。JPG 形式の画像は、Exif（Exchangeable Image File Format）のメタデータに方向情報が含まれている場合があります。この情報を使用して、画像を回転させるコードを記述できます。詳細については、「[Exif バージョン 2.32](http://cipa.jp/std/documents/download_e.html?DC-008-Translation-2019-E)」を参照してください。PNG 形式の画像には、画像の向きに関する情報は含まれていません。

 Amazon S3 バケットからイメージを渡すには、少なくとも ``AmazonS3ReadOnlyAccess 権限を持つユーザーを使用します。`AmazonRekognitionFullAccess` 権限を持つユーザーを使用して、`DetectProtectiveEquipment.` を呼び出します。

以下の入力例の JSON では、画像は Amazon S3 バケットで渡されています。詳細については、「[イメージの操作](images.md)」を参照してください。この例では、すべてのPPEタイプ（ヘッドカバー、ハンドカバー、およびフェイスカバー）の概要を最低限の検出信頼度（`MinConfidence`) の 80% で要求しています。`MinConfidence` の値は 50 ～ 100 ％ の間で指定する必要があり、`DetectProtectiveEquipment` は検出信頼度が 50 ％ ～ 100 ％ の場合のみ予測を返します。50 % 未満の値を指定すると、50 % の値を指定した結果は同じになります。詳細については、「[要約の要件を指定する](#ppe-summarization-input-parameters)」を参照してください。

```
{
    "Image": {
        "S3Object": {
            "Bucket": "amzn-s3-demo-bucket",
            "Name": "worker.jpg"
        }
    },
    "SummarizationAttributes": {
        "MinConfidence": 80,
        "RequiredEquipmentTypes": [
            "FACE_COVER",
            "HAND_COVER",
            "HEAD_COVER"
        ]
    }
}
```

処理する画像のコレクションが大きい場合、[AWS Batch](https://docs.aws.amazon.com/batch/latest/userguide/) を使用してバックグラウンドで `DetectProtectiveEquipment` への呼び出しをバッチ処理することを検討してください。

### 要約の要件を指定する
<a name="ppe-summarization-input-parameters"></a>

オプションで `SummarizationAttributes` ([ProtectiveEquipmentSummarizationAttributes](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ProtectiveEquipmentSummarizationAttributes.html)) 入力パラメータを使用すると、イメージ内で検出された PPE のタイプの要約情報をリクエストできます。

要約する PPE の種類を指定するには、`RequiredEquipmentTypes` 配列フィールドを使用します。配列には、1 つ以上のものを含めます。`FACE_COVER`、`HAND_COVER` または `HEAD_COVER` です。

`MinConfidence` フィールドを使用して、検出の最小信頼度 (50-100) を指定します。要約には、`MinConfidence` より低い信頼度で検出された、人物、身体部位、身体部位範囲、および PPE の項目は含まれません。

`DetectProtectiveEquipment` のサマリーレスポンスについては、「[保護装置の検出レスポンスの概要](#detect-protective-equipment-response)」を参照してください。



## 保護装置の検出レスポンスの概要
<a name="detect-protective-equipment-response"></a>

`DetectProtectiveEquipment` は、入力画像から検出された人物の配列を返します。各人について、検出された身体部位、および PPE の検出されたアイテムに関する情報が返されます。ヘッドカバー、ハンドカバー、フェイスカバーを着用した作業員の次の画像の JSON は以下の通りです。

![\[チェック柄のシャツ、ヘルメット、フェイスマスクを着用し、電動工具を持っている建設作業員。緑色のボックスで顔、ヘルメット、手袋をはめた手、工具が強調されている。\]](http://docs.aws.amazon.com/ja_jp/rekognition/latest/dg/images/worker-with-bb.png)


JSON では、以下の点に注意してください。
+ **検出された人物** – `Persons` は、画像上で検出された人物（PPE を着用していない人物も含む）の配列です。`DetectProtectiveEquipment` は、画像から検出された最大 15 人の PPE を検出することができます。配列内の各 [ProtectiveEquipmentPerson](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ProtectiveEquipmentPerson.html) オブジェクトには、人物 ID、人物の境界ボックス、検出された体の部位、検出された PPE のアイテムが含まれます。`Confidence` の `ProtectiveEquipmentPerson` の値は、Amazon Rekognition がバウンディングボックスに人が含まれていることを確信する割合を示します。
+ **体の部位** – `BodyParts` は、人物から検出された体の部位 ([ProtectiveEquipmentBodyPart](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ProtectiveEquipmentBodyPart.html)) の配列 (PPE でカバーされていない体の部位を含む) です。各 `ProtectiveEquipmentBodyPart` には、検出された身体部位の名称（`Name`）が含まれています。`DetectProtectEquipment` は、顔、頭、左手、右手の体の一部を検出することができます。`Confidence` の `ProtectiveEquipmentBodyPart` フィールドは、Amazon Rekognition が身体部分の検出精度に持つ信頼度のパーセンテージを示します。
+ **PPE アイテム**— 配列 `EquipmentDetections` で `ProtectiveEquipmentBodyPart` オブジェクトには、検出された PPE アイテムの配列が含まれています。各 [EquipmentDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_EquipmentDetection.html) オブジェクトには以下のフィールドが含まれています。
  +  `Type` - 検出された PPE のタイプです。
  + `BoundingBox` - 検出された PPE の周囲のバウンディングボックスです。
  + `Confidence` - Amazon Rekognition はバウンディングボックスが検出された PPE を含むと確信しています。
  + `CoversBodyPart` - 検出された PPE が対応する身体部位上にあるかどうかを示します。

  [CoversBodyPart](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CoversBodyPart.html) フィールド `Value` は、検出された PPE が対応する体の部位にあるかどうかを示すブーリアン値です。フィールド `Confidence` 予測の信頼度を示します。`CoversBodyPart` を使用すると、検出された PPE が画像内にあるが、実際には人物の上にない場合を除外することができます。
**注記**  
`CoversBodyPart` は、その人が保護具によって十分に保護されていること、または保護具自体が適切に装着されていることを示すものでも、示唆するものでもありません。
+ **概要情報** – `Summary` には、`SummarizationAttributes` の入力パラメータで指定された概要情報が含まれます。詳細については、「[要約の要件を指定する](#ppe-summarization-input-parameters)」を参照してください。

  `Summary` は、以下の情報を含むタイプ [ProtectiveEquipmentSummary](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ProtectiveEquipmentSummary.html) のオブジェクトです。
  + `PersonsWithRequiredEquipment` - 各人物が以下の条件を満たす人物の ID の配列です。
    + その人は、`SummarizationAttributes` 入力パラメータで指定された PPE をすべて着用しています。
    + `Confidence` の人物（`ProtectiveEquipmentPerson`）、身体部位（`ProtectiveEquipmentBodyPart`）、保護具（`EquipmentDetection`）が、指定された最小信頼度（`MinConfidence`）と等しいかそれ以上です。
    + PPE の全項目について `CoversBodyPart` の値が真です。
  + `PersonsWithoutRequiredEquipment` - 以下の条件のいずれかを満たす人物の ID の配列です。
    + `Confidence` の値の人物（`ProtectiveEquipmentPerson`）身体部位（`ProtectiveEquipmentBodyPart`）、身体部位カバー率（`CoversBodyPart`）は、指定された最小信頼しきい値（`MinConfidence`）よりも大きいが、人物は1つ以上の指定 PPE（`SummarizationAttributes`）が欠けています。
    + `CoversBodyPart` の値は、指定された PPE（`SummarizationAttributes`）のうち、`Confidence` の値が指定された最小信頼しきい値（`MinConfidence`）より大きいものに対して偽となります。また、指定された PPE（`SummarizationAttributes`）をすべて持ち、人物（`Confidence`）、身体部位（`ProtectiveEquipmentPerson`）、保護具（`ProtectiveEquipmentBodyPart`）の `EquipmentDetection` 値が最小信頼しきい値（`MinConfidence`）以上であることです。
  + `PersonsIndeterminate` - 人物（`Confidence`）、身体部位 （`ProtectiveEquipmentPerson`）、保護具（`ProtectiveEquipmentBodyPart`）または `EquipmentDetection` ブーリアン値の `CoversBodyPart` 値が、指定された最小信頼しきい値（`MinConfidence`）より低い場合に検出される人物の ID の配列です。

  配列サイズを使用して、特定の要約の数を取得します。例えば、`PersonsWithRequiredEquipment` のサイズは、指定されたタイプの PPE を着用していると検出された人の数を示します。

  人物 ID を使用して、人物のバウンディングボックスの位置など、人物についてのさらなる情報を調べることができます。人物 ID は、`ProtectiveEquipmentPerson`（の配列 `Persons`）で返される `ProtectiveEquipmentPerson`）オブジェクトの ID フィールドにマッピングされます。そして、対応する `ProtectiveEquipmentPerson` オブジェクトからバウンディングボックスやその他の情報を取得することができます。

```
 {
    "ProtectiveEquipmentModelVersion": "1.0",
    "Persons": [
        {
            "BodyParts": [
                {
                    "Name": "FACE",
                    "Confidence": 99.99861145019531,
                    "EquipmentDetections": [
                        {
                            "BoundingBox": {
                                "Width": 0.14528800547122955,
                                "Height": 0.14956723153591156,
                                "Left": 0.4363413453102112,
                                "Top": 0.34203192591667175
                            },
                            "Confidence": 99.90001678466797,
                            "Type": "FACE_COVER",
                            "CoversBodyPart": {
                                "Confidence": 98.0676498413086,
                                "Value": true
                            }
                        }
                    ]
                },
                {
                    "Name": "LEFT_HAND",
                    "Confidence": 96.9786376953125,
                    "EquipmentDetections": [
                        {
                            "BoundingBox": {
                                "Width": 0.14495663344860077,
                                "Height": 0.12936046719551086,
                                "Left": 0.5114737153053284,
                                "Top": 0.5744519829750061
                            },
                            "Confidence": 83.72270965576172,
                            "Type": "HAND_COVER",
                            "CoversBodyPart": {
                                "Confidence": 96.9288558959961,
                                "Value": true
                            }
                        }
                    ]
                },
                {
                    "Name": "RIGHT_HAND",
                    "Confidence": 99.82939147949219,
                    "EquipmentDetections": [
                        {
                            "BoundingBox": {
                                "Width": 0.20971858501434326,
                                "Height": 0.20528452098369598,
                                "Left": 0.2711356580257416,
                                "Top": 0.6750612258911133
                            },
                            "Confidence": 95.70789337158203,
                            "Type": "HAND_COVER",
                            "CoversBodyPart": {
                                "Confidence": 99.85433197021484,
                                "Value": true
                            }
                        }
                    ]
                },
                {
                    "Name": "HEAD",
                    "Confidence": 99.9999008178711,
                    "EquipmentDetections": [
                        {
                            "BoundingBox": {
                                "Width": 0.24350935220718384,
                                "Height": 0.34623199701309204,
                                "Left": 0.43011072278022766,
                                "Top": 0.01103297434747219
                            },
                            "Confidence": 83.88762664794922,
                            "Type": "HEAD_COVER",
                            "CoversBodyPart": {
                                "Confidence": 99.96485900878906,
                                "Value": true
                            }
                        }
                    ]
                }
            ],
            "BoundingBox": {
                "Width": 0.7403100728988647,
                "Height": 0.9412225484848022,
                "Left": 0.02214839495718479,
                "Top": 0.03134796395897865
            },
            "Confidence": 99.98855590820312,
            "Id": 0
        }
    ],
    "Summary": {
        "PersonsWithRequiredEquipment": [
            0
        ],
        "PersonsWithoutRequiredEquipment": [],
        "PersonsIndeterminate": []
    }
}
```

# 画像から個人用保護具を検出します。
<a name="ppe-procedure-image"></a>

イメージ内の人物の個人用保護具 (PPE) を検出するには、 [DetectProtectiveEquipment](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectProtectiveEquipment.html) 非ストレージ型 API オペレーションを使用します。

入力画像は、AWS SDK または AWS Command Line Interface (AWS CLI) のいずれかを使用して、入力画像を画像バイト配列 (base64 でエンコードされた画像バイト) または Amazon S3 オブジェクトとして提供できます。これらの例では、Amazon S3 バケットに保存されている画像を使用しています。詳細については、「[イメージの操作](images.md)」を参照してください。

**画像中の人物の PPE を検出するには**

1. まだ実行していない場合:

   1. `AmazonRekognitionFullAccess` と `AmazonS3ReadOnlyAccess` のアクセス権限を持つユーザーを作成または更新します。詳細については、「[ステップ 1: AWS アカウントを設定してユーザーを作成する](setting-up.md#setting-up-iam)」を参照してください。

   1. と AWS SDKs をインストール AWS CLI して設定します。詳細については、「[ステップ 2: AWS CLI と AWS SDKsを設定する](setup-awscli-sdk.md)」を参照してください。

1. S3 バケットに画像（PPE を着用した1人以上の人物を含む）をアップロードします。

   手順については、「*Amazon Simple Storage Service ユーザーガイド*」の「[Amazon S3 へのオブジェクトのアップロード](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UploadingObjectsintoAmazonS3.html)」を参照してください。

1. 以下の例を使用して、`DetectProtectiveEquipment` オペレーションを呼び出します。画像内のバウンディングボックスを表示する方法については、「[境界ボックスの表示](images-displaying-bounding-boxes.md)」を参照してください。。

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

   この例では、画像内で検出された人物で検出された PPE アイテムに関する情報を表示します。

   `amzn-s3-demo-bucket` の値を、画像が格納されている Amazon S3 バケットの名前に変更します。`photo` の値は、画像ファイル名に変更します。

   ```
   //Copyright 2020 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.client.builder.AwsClientBuilder;
   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.Image;
   import com.amazonaws.services.rekognition.model.ProtectiveEquipmentBodyPart;
   import com.amazonaws.services.rekognition.model.S3Object;
   import com.amazonaws.services.rekognition.model.ProtectiveEquipmentPerson;
   import com.amazonaws.services.rekognition.model.ProtectiveEquipmentSummarizationAttributes;
   
   import java.util.List;
   import com.amazonaws.services.rekognition.model.BoundingBox;
   import com.amazonaws.services.rekognition.model.DetectProtectiveEquipmentRequest;
   import com.amazonaws.services.rekognition.model.DetectProtectiveEquipmentResult;
   import com.amazonaws.services.rekognition.model.EquipmentDetection;
   
   
   public class DetectPPE {
   
       public static void main(String[] args) throws Exception {
   
           String photo = "photo";
           String bucket = "bucket";
   
   
           AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
           
           ProtectiveEquipmentSummarizationAttributes summaryAttributes = new ProtectiveEquipmentSummarizationAttributes()
                   .withMinConfidence(80F)
                   .withRequiredEquipmentTypes("FACE_COVER", "HAND_COVER", "HEAD_COVER");
                   
           DetectProtectiveEquipmentRequest request = new DetectProtectiveEquipmentRequest()
                   .withImage(new Image()
                           .withS3Object(new S3Object()
                                   .withName(photo).withBucket(bucket)))
                   .withSummarizationAttributes(summaryAttributes);
   
           try {
               System.out.println("Detected PPE for people in image " + photo);
               System.out.println("Detected people\n---------------");
               DetectProtectiveEquipmentResult result = rekognitionClient.detectProtectiveEquipment(request);
   
   
               List <ProtectiveEquipmentPerson> persons = result.getPersons();
   
   
               for (ProtectiveEquipmentPerson person: persons) {
                   System.out.println("ID: " + person.getId());
                   List<ProtectiveEquipmentBodyPart> bodyParts=person.getBodyParts();
                   if (bodyParts.isEmpty()){
                       System.out.println("\tNo body parts detected");
                   } else
                       for (ProtectiveEquipmentBodyPart bodyPart: bodyParts) {
                           System.out.println("\t" + bodyPart.getName() + ". Confidence: " + bodyPart.getConfidence().toString());
   
   
   
                           List<EquipmentDetection> equipmentDetections=bodyPart.getEquipmentDetections();
   
                           if (equipmentDetections.isEmpty()){
                               System.out.println("\t\tNo PPE Detected on " + bodyPart.getName());
   
                           } 
                           else {
                               for (EquipmentDetection item: equipmentDetections) {
                                   System.out.println("\t\tItem: " + item.getType() + ". Confidence: " + item.getConfidence().toString());
                                   System.out.println("\t\tCovers body part: " 
                                           + item.getCoversBodyPart().getValue().toString() + ". Confidence: " + item.getCoversBodyPart().getConfidence().toString());
   
                                   System.out.println("\t\tBounding Box");
                                   BoundingBox box =item.getBoundingBox();
   
                                   System.out.println("\t\tLeft: " +box.getLeft().toString());
                                   System.out.println("\t\tTop: " + box.getTop().toString());
                                   System.out.println("\t\tWidth: " + box.getWidth().toString());
                                   System.out.println("\t\tHeight: " + box.getHeight().toString());
                                   System.out.println("\t\tConfidence: " + item.getConfidence().toString());
                                   System.out.println();
                               }
                           }
   
                       }
               }
               System.out.println("Person ID Summary\n-----------------");
               
               //List<Integer> list=;
               DisplaySummary("With required equipment", result.getSummary().getPersonsWithRequiredEquipment());
               DisplaySummary("Without required equipment", result.getSummary().getPersonsWithoutRequiredEquipment());
               DisplaySummary("Indeterminate", result.getSummary().getPersonsIndeterminate());         
          
               
           } catch(AmazonRekognitionException e) {
               e.printStackTrace();
           }
       }
       static void DisplaySummary(String summaryType,List<Integer> idList)
       {
           System.out.print(summaryType + "\n\tIDs  ");
           if (idList.size()==0) {
               System.out.println("None");
           }
           else {
               int count=0;
               for (Integer id: idList ) { 
                   if (count++ == idList.size()-1) {
                       System.out.println(id.toString());
                   }
                   else {
                       System.out.print(id.toString() + ", ");
                   }
               }
           }
                       
           System.out.println();
           
       
       }
   }
   ```

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

   このコードは、 AWS Documentation SDK サンプル GitHub リポジトリから取得されます。詳しい事例は[こちら](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectPPE.java)です。

   ```
   //snippet-start:[rekognition.java2.detect_ppe.import]
   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.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.BoundingBox;
   import software.amazon.awssdk.services.rekognition.model.DetectProtectiveEquipmentRequest;
   import software.amazon.awssdk.services.rekognition.model.DetectProtectiveEquipmentResponse;
   import software.amazon.awssdk.services.rekognition.model.EquipmentDetection;
   import software.amazon.awssdk.services.rekognition.model.ProtectiveEquipmentBodyPart;
   import software.amazon.awssdk.services.rekognition.model.ProtectiveEquipmentSummarizationAttributes;
   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.s3.model.GetObjectRequest;
   import software.amazon.awssdk.services.s3.model.GetObjectResponse;
   import software.amazon.awssdk.services.s3.model.S3Exception;
   import software.amazon.awssdk.services.rekognition.model.ProtectiveEquipmentPerson;
   import java.io.ByteArrayInputStream;
   import java.io.InputStream;
   import java.util.List;
   //snippet-end:[rekognition.java2.detect_ppe.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 DetectPPE {
   
    public static void main(String[] args) {
   
        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_WEST_2;
        S3Client s3 = S3Client.builder()
            .region(region)
            .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
            .build();
   
        RekognitionClient rekClient = RekognitionClient.builder()
            .region(region)
            .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
            .build();
   
        displayGear(s3, rekClient, sourceImage, bucketName) ;
        s3.close();
        rekClient.close();
        System.out.println("This example is done!");
    }
   
    // snippet-start:[rekognition.java2.detect_ppe.main]
    public static void displayGear(S3Client s3,
                                   RekognitionClient rekClient,
                                   String sourceImage,
                                   String bucketName) {
   
        byte[] data = getObjectBytes (s3, bucketName, sourceImage);
        InputStream is = new ByteArrayInputStream(data);
   
        try {
            ProtectiveEquipmentSummarizationAttributes summarizationAttributes = ProtectiveEquipmentSummarizationAttributes.builder()
                .minConfidence(80F)
                .requiredEquipmentTypesWithStrings("FACE_COVER", "HAND_COVER", "HEAD_COVER")
                .build();
   
            SdkBytes sourceBytes = SdkBytes.fromInputStream(is);
            software.amazon.awssdk.services.rekognition.model.Image souImage = Image.builder()
                .bytes(sourceBytes)
                .build();
   
            DetectProtectiveEquipmentRequest request = DetectProtectiveEquipmentRequest.builder()
                .image(souImage)
                .summarizationAttributes(summarizationAttributes)
                .build();
   
            DetectProtectiveEquipmentResponse result = rekClient.detectProtectiveEquipment(request);
            List<ProtectiveEquipmentPerson> persons = result.persons();
            for (ProtectiveEquipmentPerson person: persons) {
                System.out.println("ID: " + person.id());
                List<ProtectiveEquipmentBodyPart> bodyParts=person.bodyParts();
                if (bodyParts.isEmpty()){
                    System.out.println("\tNo body parts detected");
                } else
                    for (ProtectiveEquipmentBodyPart bodyPart: bodyParts) {
                        System.out.println("\t" + bodyPart.name() + ". Confidence: " + bodyPart.confidence().toString());
                        List<EquipmentDetection> equipmentDetections=bodyPart.equipmentDetections();
   
                        if (equipmentDetections.isEmpty()){
                            System.out.println("\t\tNo PPE Detected on " + bodyPart.name());
                        } else {
                            for (EquipmentDetection item: equipmentDetections) {
                                System.out.println("\t\tItem: " + item.type() + ". Confidence: " + item.confidence().toString());
                                System.out.println("\t\tCovers body part: "
                                        + item.coversBodyPart().value().toString() + ". Confidence: " + item.coversBodyPart().confidence().toString());
   
                                System.out.println("\t\tBounding Box");
                                BoundingBox box =item.boundingBox();
                                System.out.println("\t\tLeft: " +box.left().toString());
                                System.out.println("\t\tTop: " + box.top().toString());
                                System.out.println("\t\tWidth: " + box.width().toString());
                                System.out.println("\t\tHeight: " + box.height().toString());
                                System.out.println("\t\tConfidence: " + item.confidence().toString());
                                System.out.println();
                            }
                        }
                    }
            }
            System.out.println("Person ID Summary\n-----------------");
   
            displaySummary("With required equipment", result.summary().personsWithRequiredEquipment());
            displaySummary("Without required equipment", result.summary().personsWithoutRequiredEquipment());
            displaySummary("Indeterminate", result.summary().personsIndeterminate());
   
        } catch (RekognitionException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
   
    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;
    }
   
    static void displaySummary(String summaryType,List<Integer> idList) {
        System.out.print(summaryType + "\n\tIDs  ");
        if (idList.size()==0) {
            System.out.println("None");
        } else {
            int count=0;
            for (Integer id: idList ) {
                if (count++ == idList.size()-1) {
                    System.out.println(id.toString());
                } else {
                    System.out.print(id.toString() + ", ");
                }
            }
        }
        System.out.println();
    }
    // snippet-end:[rekognition.java2.detect_ppe.main]
   }
   ```

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

   この AWS CLI コマンドは PPE の概要をリクエストし、CLI オペレーションの JSON `detect-protective-equipment` 出力を表示します。

   `amzn-s3-demo-bucket` は、画像が含まれている Amazon S3 バケットの名前に変更します。`input.jpg` を使用する画像の名前に変更します。

   ```
   aws rekognition detect-protective-equipment \
     --image "S3Object={Bucket=amzn-s3-demo-bucket,Name=input.jpg}" \
     --summarization-attributes "MinConfidence=80,RequiredEquipmentTypes=['FACE_COVER','HAND_COVER','HEAD_COVER']"
   ```

   この AWS CLI コマンドは、 CLI オペレーションの JSON `detect-protective-equipment` 出力を表示します。

   `amzn-s3-demo-bucket` は、画像が含まれている Amazon S3 バケットの名前に変更します。`input.jpg` を使用する画像の名前に変更します。

   ```
   aws rekognition detect-protective-equipment \
     --image "S3Object={Bucket=amzn-s3-demo-bucket,Name=input.jpg}"
   ```

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

   この例では、画像内で検出された人物で検出された PPE アイテムに関する情報を表示します。

   `amzn-s3-demo-bucket` の値を、画像が格納されている Amazon S3 バケットの名前に変更します。`photo` の値は、画像ファイル名に変更します。Rekognition セッションを作成する行の `profile_name` の値を、自分のデベロッパープロファイル名に置き換えます。

   ```
   # Copyright 2020 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_ppe(photo, bucket):
   
       session = boto3.Session(profile_name='profile-name')
       client = session.client('rekognition')
   
       response = client.detect_protective_equipment(Image={'S3Object': {'Bucket': bucket, 'Name': photo}},
                                                     SummarizationAttributes={'MinConfidence': 80,
                                                                              'RequiredEquipmentTypes': ['FACE_COVER',
                                                                                                         'HAND_COVER',
                                                                                                         'HEAD_COVER']})
   
       print('Detected PPE for people in image ' + photo)
       print('\nDetected people\n---------------')
       for person in response['Persons']:
   
           print('Person ID: ' + str(person['Id']))
           print('Body Parts\n----------')
           body_parts = person['BodyParts']
           if len(body_parts) == 0:
               print('No body parts found')
           else:
               for body_part in body_parts:
                   print('\t' + body_part['Name'] + '\n\t\tConfidence: ' + str(body_part['Confidence']))
                   print('\n\t\tDetected PPE\n\t\t------------')
                   ppe_items = body_part['EquipmentDetections']
                   if len(ppe_items) == 0:
                       print('\t\tNo PPE detected on ' + body_part['Name'])
                   else:
                       for ppe_item in ppe_items:
                           print('\t\t' + ppe_item['Type'] + '\n\t\t\tConfidence: ' + str(ppe_item['Confidence']))
                           print('\t\tCovers body part: ' + str(
                               ppe_item['CoversBodyPart']['Value']) + '\n\t\t\tConfidence: ' + str(
                               ppe_item['CoversBodyPart']['Confidence']))
                           print('\t\tBounding Box:')
                           print('\t\t\tTop: ' + str(ppe_item['BoundingBox']['Top']))
                           print('\t\t\tLeft: ' + str(ppe_item['BoundingBox']['Left']))
                           print('\t\t\tWidth: ' + str(ppe_item['BoundingBox']['Width']))
                           print('\t\t\tHeight: ' + str(ppe_item['BoundingBox']['Height']))
                           print('\t\t\tConfidence: ' + str(ppe_item['Confidence']))
               print()
           print()
   
       print('Person ID Summary\n----------------')
       display_summary('With required equipment', response['Summary']['PersonsWithRequiredEquipment'])
       display_summary('Without required equipment', response['Summary']['PersonsWithoutRequiredEquipment'])
       display_summary('Indeterminate', response['Summary']['PersonsIndeterminate'])
   
       print()
       return len(response['Persons'])
   
   # Display summary information for supplied summary.
   def display_summary(summary_type, summary):
       print(summary_type + '\n\tIDs: ', end='')
       if (len(summary) == 0):
           print('None')
       else:
           for num, id in enumerate(summary, start=0):
               if num == len(summary) - 1:
                   print(id)
               else:
                   print(str(id) + ', ', end='')
   
   def main():
       photo = 'photo-name'
       bucket = 'amzn-s3-demo-bucket'
       person_count = detect_ppe(photo, bucket)
       print("Persons detected: " + str(person_count))
   
   if __name__ == "__main__":
       main()
   ```

------

# 例：フェイスカバーの周りにバウンディングボックスを描画する
<a name="ppe-example-image-bounding-box"></a>

次の例は、人物で検出されたフェイスカバーの周りにバウンディングボックスを描画する方法を示しています。 AWS Lambda と Amazon DynamoDB を使用する例については、[AWS 「Documentation SDK examples GitHub repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javav2/usecases/creating_lambda_ppe)」を参照してください。

フェイスカバーを検出するには、[DetectProtectiveEquipment](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectProtectiveEquipment.html) 非ストレージ型 API オペレーションを使用します。画像は、ローカルファイルシステムから読み込まれます。入力画像は、画像バイト配列（base64 エンコードされた画像バイト）として `DetectProtectiveEquipment` に提供されます。詳細については、「[イメージの操作](images.md)」を参照してください。

この例では、検出された顔面領域のバウンディングボックスが表示されます。フェイスカバーが体の一部を完全に覆っている場合、バウンディングボックスは緑色で表示されます。それ以外の場合は、赤色のバウンディングボックスが表示されます。また、検出の信頼度が指定した信頼度より低い場合は、警告としてフェイスカバーのバウンディングボックス内に黄色のバウンディングボックスが表示されます。フェイスカバーが検出されなかった場合は、人物の周囲に赤色のバウンディングボックスが描画されます。

出力される画像は以下のようなものです。

![\[倉庫で働く 4 人の作業員。高視認性ベスト、ヘルメット、安全ゴーグル、マスクを着用している。マスクが境界ボックスで囲まれている。\]](http://docs.aws.amazon.com/ja_jp/rekognition/latest/dg/images/workers-with-bb.png)


**検出されたフェイスカバーのバウンディングボックスを表示するには**

1. まだ実行していない場合:

   1. `AmazonRekognitionFullAccess` アクセス権限を持つユーザーを作成または更新します。詳細については、「[ステップ 1: AWS アカウントを設定してユーザーを作成する](setting-up.md#setting-up-iam)」を参照してください。

   1. と AWS SDKs をインストール AWS CLI して設定します。詳細については、「[ステップ 2: AWS CLI と AWS SDKsを設定する](setup-awscli-sdk.md)」を参照してください。

1. 以下の例を使用して、`DetectProtectiveEquipment` オペレーションを呼び出します。画像内のバウンディングボックスの表示については、「[境界ボックスの表示](images-displaying-bounding-boxes.md)」を参照してください。。

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

   関数 `main` の中で、以下を変更します。
   + `photo` の値をローカル画像ファイル（PNG または JPEG）のパスとファイル名に変更します。
   + `confidence` の値を任意の信頼度（50～100）に変更します。

   ```
   //Loads images, detects faces and draws bounding boxes.Determines exif orientation, if necessary.
   package com.amazonaws.samples;
   
   
   import java.awt.*;
   import java.awt.image.BufferedImage;
   import java.util.List;
   import javax.imageio.ImageIO;
   import javax.swing.*;
   
   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 com.amazonaws.util.IOUtils;
   
   import com.amazonaws.client.builder.AwsClientBuilder;
   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.DetectProtectiveEquipmentRequest;
   import com.amazonaws.services.rekognition.model.DetectProtectiveEquipmentResult;
   import com.amazonaws.services.rekognition.model.EquipmentDetection;
   import com.amazonaws.services.rekognition.model.Image;
   import com.amazonaws.services.rekognition.model.ProtectiveEquipmentBodyPart;
   import com.amazonaws.services.rekognition.model.ProtectiveEquipmentPerson;
   
   // Calls DetectFaces and displays a bounding box around each detected image.
   public class PPEBoundingBox extends JPanel {
   
       private static final long serialVersionUID = 1L;
   
       BufferedImage image;
       static int scale;
       DetectProtectiveEquipmentResult result;
       float confidence=80;
   
       public PPEBoundingBox(DetectProtectiveEquipmentResult ppeResult, BufferedImage bufImage, float requiredConfidence) throws Exception {
           super();
           scale = 2; // increase to shrink image size.
   
           result = ppeResult;
           image = bufImage;
           
           confidence=requiredConfidence;
       }
       // 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);
           int offset=20;
   
           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 detected persons and display bounding boxes.
           List<ProtectiveEquipmentPerson> persons = result.getPersons();
   
           for (ProtectiveEquipmentPerson person: persons) {
               BoundingBox boxPerson = person.getBoundingBox();
               left = width * boxPerson.getLeft();
               top = height * boxPerson.getTop();
               Boolean foundMask=false;
   
               List<ProtectiveEquipmentBodyPart> bodyParts=person.getBodyParts();
               
               if (bodyParts.isEmpty()==false)
                {
                       //body parts detected
   
                       for (ProtectiveEquipmentBodyPart bodyPart: bodyParts) {
   
                           List<EquipmentDetection> equipmentDetections=bodyPart.getEquipmentDetections();
   
                           for (EquipmentDetection item: equipmentDetections) {
   
                               if (item.getType().contentEquals("FACE_COVER"))
                               {
                                   // Draw green or red bounding box depending on mask coverage.
                                   foundMask=true;
                                   BoundingBox box =item.getBoundingBox();
                                   left = width * box.getLeft();
                                   top = height * box.getTop();
                                   Color maskColor=new Color( 0, 212, 0);
   
                                   if (item.getCoversBodyPart().getValue()==false) {
                                       // red bounding box
                                       maskColor=new Color( 255, 0, 0);
                                   }
                                   g2d.setColor(maskColor);
                                   g2d.drawRect(Math.round(left / scale), Math.round(top / scale),
                                           Math.round((width * box.getWidth()) / scale), Math.round((height * box.getHeight())) / scale);
                                   
                                   // Check confidence is > supplied confidence.
                                   if (item.getCoversBodyPart().getConfidence()< confidence)
                                   {
                                       // Draw a yellow bounding box inside face mask bounding box 
                                       maskColor=new Color( 255, 255, 0);
                                       g2d.setColor(maskColor);
                                       g2d.drawRect(Math.round((left + offset) / scale),
                                                Math.round((top + offset) / scale),
                                                Math.round((width * box.getWidth())- (offset * 2 ))/ scale,
                                                Math.round((height * box.getHeight()) -( offset* 2)) / scale);
                                   }
   
                               }
                           }
   
                       }
   
                   } 
   
               // Didn't find a mask, so draw person bounding box red
               if (foundMask==false) {
   
                   left = width * boxPerson.getLeft();
                   top = height * boxPerson.getTop();
                   g2d.setColor(new Color(255, 0, 0));
                   g2d.drawRect(Math.round(left / scale), Math.round(top / scale),
                           Math.round(((width) * boxPerson.getWidth()) / scale), Math.round((height * boxPerson.getHeight())) / scale);
               }
            }  
            
       }
   
   
       public static void main(String arg[]) throws Exception {
   
           String photo = "photo";
           
           float confidence =80;
   
     
           int height = 0;
           int width = 0;
   
           BufferedImage image = null;
           ByteBuffer imageBytes;
           
           // Get image bytes for call to DetectProtectiveEquipment
           try (InputStream inputStream = new FileInputStream(new File(photo))) {
               imageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream));
           }
           
           //Get image for display
           InputStream imageBytesStream;
           imageBytesStream = new ByteArrayInputStream(imageBytes.array());
   
           ByteArrayOutputStream baos = new ByteArrayOutputStream();
           image=ImageIO.read(imageBytesStream);
           ImageIO.write(image, "jpg", baos);
           width = image.getWidth();
           height = image.getHeight();
    
           //Get Rekognition client
           AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
           
          
           // Call DetectProtectiveEquipment
           DetectProtectiveEquipmentRequest request = new DetectProtectiveEquipmentRequest()
                   .withImage(new Image()
                           .withBytes(imageBytes));
   
           DetectProtectiveEquipmentResult result = rekognitionClient.detectProtectiveEquipment(request);
   
   
           // Create frame and panel.
           JFrame frame = new JFrame("Detect PPE");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           PPEBoundingBox panel = new PPEBoundingBox(result, image, confidence);
           panel.setPreferredSize(new Dimension(image.getWidth() / scale, image.getHeight() / scale));
           frame.setContentPane(panel);
           frame.pack();
           frame.setVisible(true);
   
       }
   }
   ```

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

   このコードは、 AWS Documentation SDK サンプル GitHub リポジトリから取得されます。詳しい事例は [こちら](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/PPEBoundingBoxFrame.java) です。

   ```
   import java.awt.*;
   import java.awt.image.BufferedImage;
   import java.io.*;
   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.BoundingBox;
   import software.amazon.awssdk.services.rekognition.model.DetectProtectiveEquipmentRequest;
   import software.amazon.awssdk.services.rekognition.model.EquipmentDetection;
   import software.amazon.awssdk.services.rekognition.model.ProtectiveEquipmentBodyPart;
   import software.amazon.awssdk.services.rekognition.model.ProtectiveEquipmentPerson;
   import software.amazon.awssdk.services.rekognition.model.ProtectiveEquipmentSummarizationAttributes;
   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;
   import software.amazon.awssdk.services.rekognition.model.DetectProtectiveEquipmentResponse;
   //snippet-end:[rekognition.java2.display_mask.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 PPEBoundingBoxFrame extends JPanel {
   
    DetectProtectiveEquipmentResponse result;
    static BufferedImage image;
    static int scale;
    float confidence;
   
    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 that shows a person wearing a mask (for example, masks.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();
   
        displayGear(s3, rekClient, sourceImage, bucketName);
        s3.close();
        rekClient.close();
    }
   
    // snippet-start:[rekognition.java2.display_mask.main]
   public static void displayGear(S3Client s3,
                                       RekognitionClient rekClient,
                                       String sourceImage,
                                       String bucketName) {
       float confidence = 80;
       byte[] data = getObjectBytes(s3, bucketName, sourceImage);
       InputStream is = new ByteArrayInputStream(data);
   
       try {
           ProtectiveEquipmentSummarizationAttributes summarizationAttributes = ProtectiveEquipmentSummarizationAttributes.builder()
               .minConfidence(70F)
               .requiredEquipmentTypesWithStrings("FACE_COVER")
               .build();
   
           SdkBytes sourceBytes = SdkBytes.fromInputStream(is);
           image = ImageIO.read(sourceBytes.asInputStream());
   
           // Create an Image object for the source image.
           software.amazon.awssdk.services.rekognition.model.Image souImage = Image.builder()
               .bytes(sourceBytes)
               .build();
   
           DetectProtectiveEquipmentRequest request = DetectProtectiveEquipmentRequest.builder()
               .image(souImage)
               .summarizationAttributes(summarizationAttributes)
               .build();
   
           DetectProtectiveEquipmentResponse result = rekClient.detectProtectiveEquipment(request);
           JFrame frame = new JFrame("Detect PPE");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           PPEBoundingBoxFrame panel = new PPEBoundingBoxFrame(result, image, confidence);
           panel.setPreferredSize(new Dimension(image.getWidth() / scale, image.getHeight() / scale));
           frame.setContentPane(panel);
           frame.pack();
           frame.setVisible(true);
   
       } catch (RekognitionException e) {
           e.printStackTrace();
           System.exit(1);
       } catch (Exception 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 PPEBoundingBoxFrame(DetectProtectiveEquipmentResponse ppeResult, BufferedImage bufImage, float requiredConfidence) {
        super();
        scale = 1; // increase to shrink image size.
        result = ppeResult;
        image = bufImage;
        confidence=requiredConfidence;
    }
   
    // Draws the bounding box around the detected masks.
    public void paintComponent(Graphics g) {
        float left = 0;
        float top = 0;
        int height = image.getHeight(this);
        int width = image.getWidth(this);
        int offset=20;
   
        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 detected persons and display bounding boxes.
        List<ProtectiveEquipmentPerson> persons = result.persons();
        for (ProtectiveEquipmentPerson person: persons) {
   
            List<ProtectiveEquipmentBodyPart> bodyParts=person.bodyParts();
            if (!bodyParts.isEmpty()){
                for (ProtectiveEquipmentBodyPart bodyPart: bodyParts) {
                    List<EquipmentDetection> equipmentDetections=bodyPart.equipmentDetections();
                    for (EquipmentDetection item: equipmentDetections) {
   
                        String myType = item.type().toString();
                        if (myType.compareTo("FACE_COVER") ==0) {
   
                            // Draw green bounding box depending on mask coverage.
                            BoundingBox box =item.boundingBox();
                            left = width * box.left();
                            top = height * box.top();
                            Color maskColor=new Color( 0, 212, 0);
   
                            if (item.coversBodyPart().equals(false)) {
                                // red bounding box.
                                maskColor=new Color( 255, 0, 0);
                            }
                            g2d.setColor(maskColor);
                            g2d.drawRect(Math.round(left / scale), Math.round(top / scale),
                                    Math.round((width * box.width()) / scale), Math.round((height * box.height())) / scale);
   
                            // Check confidence is > supplied confidence.
                            if (item.coversBodyPart().confidence() < confidence) {
                                // Draw a yellow bounding box inside face mask bounding box.
                                maskColor=new Color( 255, 255, 0);
                                g2d.setColor(maskColor);
                                g2d.drawRect(Math.round((left + offset) / scale),
                                        Math.round((top + offset) / scale),
                                        Math.round((width * box.width())- (offset * 2 ))/ scale,
                                        Math.round((height * box.height()) -( offset* 2)) / scale);
                            }
                        }
                    }
                }
            }
       }
    }
    // snippet-end:[rekognition.java2.display_mask.main]
   }
   ```

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

   関数 `main` の中で、以下を変更します。
   + `photo` の値をローカル画像ファイル（PNG または JPEG）のパスとファイル名に変更します。
   + `confidence` の値を任意の信頼度（50～100）に変更します。
   +  Rekognition セッションを作成する行の `profile_name` の値を、自分のデベロッパープロファイル名に置き換えます。

   ```
   #Copyright 2020 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, ImageDraw, ExifTags, ImageColor
   
   def detect_ppe(photo, confidence):
   
       fill_green='#00d400'
       fill_red='#ff0000'
       fill_yellow='#ffff00'
       line_width=3
   
       #open image and get image data from stream.
       image = Image.open(open(photo,'rb'))
       stream = io.BytesIO()
       image.save(stream, format=image.format)    
       image_binary = stream.getvalue()
       imgWidth, imgHeight = image.size  
       draw = ImageDraw.Draw(image)  
   
       client=boto3.client('rekognition')
   
       response = client.detect_protective_equipment(Image={'Bytes': image_binary})
   
       for person in response['Persons']:
           
           found_mask=False
   
           for body_part in person['BodyParts']:
               ppe_items = body_part['EquipmentDetections']
                    
               for ppe_item in ppe_items:
                   #found a mask 
                   if ppe_item['Type'] == 'FACE_COVER':
                       fill_color=fill_green
                       found_mask=True
                       # check if mask covers face
                       if ppe_item['CoversBodyPart']['Value'] == False:
                           fill_color=fill='#ff0000'
                       # draw bounding box around mask
                       box = ppe_item['BoundingBox']
                       left = imgWidth * box['Left']
                       top = imgHeight * box['Top']
                       width = imgWidth * box['Width']
                       height = imgHeight * box['Height']
                       points = (
                               (left,top),
                               (left + width, top),
                               (left + width, top + height),
                               (left , top + height),
                               (left, top)
                           )
                       draw.line(points, fill=fill_color, width=line_width)
   
                        # Check if confidence is lower than supplied value       
                       if ppe_item['CoversBodyPart']['Confidence'] < confidence:
                           #draw warning yellow bounding box within face mask bounding box
                           offset=line_width+ line_width 
                           points = (
                                       (left+offset,top + offset),
                                       (left + width-offset, top+offset),
                                       ((left) + (width-offset), (top-offset) + (height)),
                                       (left+ offset , (top) + (height -offset)),
                                       (left + offset, top + offset)
                                   )
                           draw.line(points, fill=fill_yellow, width=line_width)
                   
           if found_mask==False:
               # no face mask found so draw red bounding box around body
               box = person['BoundingBox']
               left = imgWidth * box['Left']
               top = imgHeight * box['Top']
               width = imgWidth * box['Width']
               height = imgHeight * box['Height']
               points = (
                   (left,top),
                   (left + width, top),
                   (left + width, top + height),
                   (left , top + height),
                   (left, top)
                   )
               draw.line(points, fill=fill_red, width=line_width)
   
       image.show()
   
   def main():
       photo='photo'
       confidence=80
       detect_ppe(photo, confidence)
   
   if __name__ == "__main__":
       main()
   ```

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

   次の CLI の例では、以下の引数の値を変更します。
   + `photo` の値をローカル画像ファイル（PNG または JPEG）のパスとファイル名に変更します。
   + `confidence` の値を任意の信頼度（50～100）に変更します。
   +  Rekognition セッションを作成する行の `profile_name` の値を、自分のデベロッパープロファイル名に置き換えます。

   ```
                                   aws rekognition detect-protective-equipment  --image "{"S3Object":{"Bucket":"amzn-s3-demo-bucket","Name":"image-name"}}" --profile profile-name \ 
                                   --summarization-attributes "{"MinConfidence":MinConfidenceNumber,"RequiredEquipmentTypes":["FACE_COVER"]}"
   ```

    Windows デバイスで CLI にアクセスする場合は、パーサーエラーの発生に対処するため、一重引用符の代わりに二重引用符を使用し、内側の二重引用符をバックスラッシュ (\$1) でエスケープします。例として以下を参照してください。

   ```
                                   aws rekognition detect-protective-equipment  --image "{\"S3Object\":{\"Bucket\":\"amzn-s3-demo-bucket\",\"Name\":\"image-name\"}}" \ 
                                   --profile profile-name --summarization-attributes "{\"MinConfidence\":MinConfidenceNumber,\"RequiredEquipmentTypes\":[\"FACE_COVER\"]}"
   ```

------