

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# Mendeteksi alat pelindung diri
<a name="ppe-detection"></a>

Amazon Rekognition dapat mendeteksi Alat Pelindung Diri (APD) yang dikenakan oleh orang-orang dalam citra. Anda dapat menggunakan informasi ini untuk meningkatkan praktik keselamatan di tempat kerja. Misalnya, Anda dapat menggunakan pendeteksian APD untuk membantu menentukan apakah pekerja di lokasi konstruksi mengenakan penutup kepala, atau jika petugas medis mengenakan penutup wajah dan penutup tangan. Citra berikut menunjukkan beberapa tipe APD yang dapat dideteksi.

![\[Pekerja yang memakai APD termasuk hardhat, kacamata pengaman, masker pelindung, dan sarung tangan, mengoperasikan perkakas listrik. Membatasi kotak di sekitar item.\]](http://docs.aws.amazon.com/id_id/rekognition/latest/dg/images/worker-with-bb.png)


Untuk mendeteksi APD dalam citra, panggil API [DetectProtectiveEquipment](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectProtectiveEquipment.html) dan teruskan citra input. Respons adalah struktur JSON yang meliputi hal berikut ini.
+ Orang-orang yang terdeteksi dalam citra.
+ Bagian tubuh tempat APD dipakai (wajah, kepala, tangan kiri, dan tangan kanan).
+ tipe APD yang terdeteksi pada bagian tubuh (penutup wajah, penutup tangan, dan penutup kepala). 
+ Untuk item APD yang terdeteksi, indikator apakah APD menutupi bagian tubuh yang sesuai atau tidak.

Kotak batas dikembalikan untuk lokasi orang dan item APD yang terdeteksi pada citra. 

Atau, Anda dapat meminta ringkasan item APD dan orang yang terdeteksi dalam citra. Untuk informasi selengkapnya, lihat [Meringkas APD yang terdeteksi dalam sebuah citra](#ppe-summarization). 

**catatan**  
Deteksi APD Amazon Rekognition tidak melakukan pengenalan wajah atau perbandingan wajah, dan tidak dapat mengidentifikasi orang yang terdeteksi. 

## Tipe APD
<a name="ppe-types"></a>

[DetectProtectiveEquipment](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectProtectiveEquipment.html) mendeteksi tipe APD berikut. Jika Anda ingin mendeteksi tipe APD lainnya dalam citra, pertimbangkan untuk menggunakan label kustom Amazon Rekognition untuk melatih model kustom. Untuk informasi selengkapnya, lihat [Label Kustom Amazon Rekognition](https://docs.aws.amazon.com/rekognition/latest/customlabels-dg/what-is.html).

### Penutup wajah
<a name="ppe-face-cover"></a>

`DetectProtectiveEquipment` dapat mendeteksi penutup wajah umum seperti masker bedah, N95, dan masker yang terbuat dari kain. 

### Penutup tangan
<a name="ppe-hand-cover"></a>

`DetectProtectiveEquipment` dapat mendeteksi penutup tangan seperti sarung tangan bedah dan sarung tangan pengaman. 

### Penutup kepala
<a name="ppe-head-cover"></a>

`DetectProtectiveEquipment` dapat mendeteksi topi dan helm keras. 

API menunjukkan bahwa penutup kepala, tangan, atau wajah terdeteksi dalam citra. API tidak mengembalikan informasi tentang tipe penutup tertentu. Misalnya, 'sarung tangan bedah' untuk tipe penutup tangan. 

## kepercayaan deteksi APD
<a name="ppe-confidence"></a>

Amazon Rekognition membuat prediksi tentang kehadiran APD, orang, dan bagian tubuh dalam citra. API memberikan skor (50-100) yang menunjukkan tingginya kepercayaan Amazon Rekognition dalam akurasi prediksi. 

**catatan**  
Jika Anda berencana untuk menggunakan operasi `DetectProtectiveEquipment` untuk membuat keputusan yang memengaruhi hak, privasi, atau akses seseorang ke layanan, maka kami sarankan supaya Anda memberikan hasilnya kepada manusia untuk ditinjau dan divalidasi sebelum mengambil tindakan. 

## Meringkas APD yang terdeteksi dalam sebuah citra
<a name="ppe-summarization"></a>

Anda dapat meminta ringkasan item APD dan orang yang terdeteksi dalam citra. Anda dapat menentukan daftar alat pelindung yang diperlukan (penutup wajah, penutup tangan, atau penutup kepala) dan ambang batas kepercayaan minimum (misalnya, 80%). Respons tersebut mencakup ringkasan pengenal per citra (ID) terkonsolidasi dari orang-orang dengan APD yang diperlukan, orang tanpa APD yang diperlukan, dan orang-orang yang membuat ketentuan tidak dapat ditetapkan. 

Ringkasan ini memungkinkan Anda untuk dengan cepat menjawab pertanyaan seperti *Berapa banyak orang yang tidak memakai penutup wajah?* atau *Apakah semua orang memakai APD?* Setiap orang yang terdeteksi dalam ringkasan memiliki ID yang unik. Anda dapat menggunakan informasi temukan ID seperti lokasi kotak batas seseorang yang tidak memakai APD. 

**catatan**  
ID dibuat secara acak berdasarkan analisis per citra dan tidak konsisten di seluruh citra atau beberapa analisis dari citra yang sama.

Anda dapat meringkas penutup wajah, penutup kepala, penutup tangan, atau kombinasi pilihan Anda. Untuk menentukan tipe APD yang diperlukan, lihat [Menentukan persyaratan peringkasan](ppe-request-response.md#ppe-summarization-input-parameters). Anda juga dapat menentukan tingkat kepercayaan minimum (50-100) yang harus dipenuhi dalam setiap deteksi untuk dimasukkan dalam ringkasan. 

 Untuk informasi selengkapnya tentang respons ringkasan dari `DetectProtectiveEquipment`, lihat [Memahami DetectProtectiveEquipment tanggapannya](ppe-request-response.md#detect-protective-equipment-response).

## Tutorial: Membuat AWS Lambda fungsi yang mendeteksi gambar dengan APD
<a name="ppe-tutorial-lambda"></a>

Anda dapat membuat AWS Lambda fungsi yang mendeteksi alat pelindung diri (APD) dalam gambar yang terletak di ember Amazon S3. Lihat [contoh GitHub repositori AWS Documentation SDK](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javav2/usecases/creating_lambda_ppe) untuk tutorial Java V2 ini.

# Memahami API deteksi alat pelindung diri
<a name="ppe-request-response"></a>

Informasi berikut menjelaskan API [DetectProtectiveEquipment](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectProtectiveEquipment.html). Untuk kode sampel, lihat [Mendeteksi alat pelindung diri dalam citra](ppe-procedure-image.md).

## Menyuplai citra
<a name="detect-protective-equipment-request"></a>

Anda dapat memberikan citra input (JPG atau format PNG), baik sebagai bit citra atau pun referensi citra yang disimpan dalam bucket Amazon S3. 

Sebaiknya gunakan citra yang menunjukkan wajah orang tersebut menghadap ke kamera.

Jika citra input Anda tidak diputar ke orientasi 0 derajat, sebaiknya putar ke orientasi 0 derajat sebelum mengirimkannya ke `DetectProtectiveEquipment`. Citra dalam format JPG mungkin berisi informasi orientasi dalam metadata format (Exif) file citra yang dapat ditukar. Anda dapat menggunakan informasi ini untuk menulis kode yang memutar citra Anda. Untuk informasi selengkapnya, lihat [Exif versi 2.32](http://cipa.jp/std/documents/download_e.html?DC-008-Translation-2019-E). Citra format PNG tidak berisi informasi orientasi citra. 

 Untuk meneruskan gambar dari bucket Amazon S3, gunakan pengguna dengan setidaknya priviliges `` ReadOnlyAccess AmazonS3. Gunakan pengguna dengan `AmazonRekognitionFullAccess` priviliges untuk menelepon `DetectProtectiveEquipment.` 

Pada contoh JSON input berikut, citra dilewatkan dalam bucket Amazon S3. Untuk informasi selengkapnya, lihat [Bekerja dengan citra](images.md). Contoh meminta ringkasan semua tipe APD (penutup kepala, penutup tangan, dan penutup wajah) dengan kepercayaan pendeteksian minimal (`MinConfidence`) dari 80%. Anda harus menentukan nilai `MinConfidence` yang berada antara 50-100% sebagai prediksi kembali `DetectProtectiveEquipment` hanya jika tingkat kepercayaan pendeteksian berada antara 50% - 100%. Jika Anda menentukan nilai yang kurang dari 50%, hasilnya sama dengan menentukan nilai 50%. Untuk informasi selengkapnya, lihat [Menentukan persyaratan peringkasan](#ppe-summarization-input-parameters). 

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

Jika koleksi citra yang akan diproses cukup besar, pertimbangkan untuk menggunakan [AWS Batch](https://docs.aws.amazon.com/batch/latest/userguide/) untuk memproses panggilan ke `DetectProtectiveEquipment` dalam batch di latar belakang. 

### Menentukan persyaratan peringkasan
<a name="ppe-summarization-input-parameters"></a>

Anda dapat secara opsional menggunakan parameter input `SummarizationAttributes` ([ProtectiveEquipmentSummarizationAttributes](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ProtectiveEquipmentSummarizationAttributes.html)) untuk meminta informasi ringkasan untuk tipe APD yang terdeteksi dalam citra.

Untuk menentukan tipe APD untuk meringkas, gunakan bidang array `RequiredEquipmentTypes`. Dalam array, masukkan satu atau beberapa `FACE_COVER`, `HAND_COVER` atau `HEAD_COVER`. 

Gunakan `MinConfidence` untuk menentukan kepercayaan pendeteksian minimum (50-100). Ringkasan tidak termasuk Orang, bagian tubuh, cakupan bagian tubuh, dan item APD, yang terdeteksi dengan kepercayaan kurang dari `MinConfidence`.

Untuk informasi tentang respons ringkasan dari `DetectProtectiveEquipment`, lihat [Memahami DetectProtectiveEquipment tanggapannya](#detect-protective-equipment-response). 



## Memahami DetectProtectiveEquipment tanggapannya
<a name="detect-protective-equipment-response"></a>

`DetectProtectiveEquipment` mengembalikan array orang yang terdeteksi dalam citra input. Untuk setiap orang, informasi tentang bagian tubuh yang terdeteksi dan item APD yang terdeteksi dikembalikan. JSON untuk citra seorang pekerja yang mengenakan penutup kepala, penutup tangan, dan penutup wajah adalah sebagai berikut.

![\[Pekerja konstruksi mengenakan kemeja kotak-kotak, topi keras dan masker wajah memegang alat listrik. Kotak hijau menonjolkan wajah, topi keras, tangan bersarung tangan, dan alat.\]](http://docs.aws.amazon.com/id_id/rekognition/latest/dg/images/worker-with-bb.png)


Dalam JSON, perhatikan hal berikut.
+ **Orang yang terdeteksi** — `Persons` adalah array orang yang terdeteksi pada citra (termasuk orang yang tidak memakai APD). `DetectProtectiveEquipment` dapat mendeteksi APD pada hingga 15 orang yang terdeteksi dalam sebuah citra. Setiap objek [ProtectiveEquipmentPerson](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ProtectiveEquipmentPerson.html) dalam array berisi ID orang, kotak pembatas untuk orang, bagian tubuh yang terdeteksi, dan item APD yang terdeteksi. Nilai dari `Confidence` dalam `ProtectiveEquipmentPerson` menunjukkan persentase kepercayaan yang dimiliki Amazon Rekognition jika kotak pembatas tersebut berisi seseorang.
+ **Bagian Tubuh** — `BodyParts` adalah array dari bagian tubuh ([ProtectiveEquipmentBodyPart](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ProtectiveEquipmentBodyPart.html)) yang terdeteksi pada seseorang (termasuk bagian tubuh yang tidak tertutup oleh APD). Setiap `ProtectiveEquipmentBodyPart` termasuk nama (`Name`) dari bagian tubuh yang terdeteksi. `DetectProtectEquipment` dapat mendeteksi bagian tubuh wajah, kepala, tangan kiri, dan tangan kanan. Bidang `Confidence` dalam `ProtectiveEquipmentBodyPart` menunjukkan persentase keyakinan yang dimiliki Amazon Rekognition dalam akurasi deteksi bagian tubuh. 
+ **Item PPE** — `EquipmentDetections` array dalam objek `ProtectiveEquipmentBodyPart` berisi array item APD yang terdeteksi. Tiap objek [EquipmentDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_EquipmentDetection.html) berisi kolom-kolom berikut. 
  +  `Type` — tipe APD yang terdeteksi.
  + `BoundingBox` — kotak pembatas di sekitar APD yang terdeteksi.
  + `Confidence` — kepercayaan yang dimiliki Amazon Rekognition bahwa kotak pembatas berisi APD yang terdeteksi.
  + `CoversBodyPart` — Menunjukkan jika APD yang terdeteksi berada di bagian tubuh yang sesuai.

  Bidang [CoversBodyPart](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CoversBodyPart.html) `Value` adalah nilai boolean yang menunjukkan jika APD yang terdeteksi berada di bagian tubuh yang sesuai. Bidang `Confidence` menunjukkan kepercayaan dalam prediksi. Anda dapat menggunakan `CoversBodyPart` untuk memfilter kasus yang APDnya terdeteksi di dalam citra, namun tidak benar-benar pada orang tersebut. 
**catatan**  
`CoversBodyPart` tidak menunjukkan, atau menyiratkan, bahwa orang tersebut dilindungi secara memadai oleh peralatan pelindung atau bahwa peralatan pelindung itu sendiri sudah dipakai dengan benar. 
+ **Informasi ringkasan** — `Summary` berisi informasi ringkasan yang ditentukan dalam parameter input `SummarizationAttributes`. Untuk informasi selengkapnya, lihat [Menentukan persyaratan peringkasan](#ppe-summarization-input-parameters).

  `Summary` adalah obyek dari tipe [ProtectiveEquipmentSummary](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ProtectiveEquipmentSummary.html) yang berisi informasi berikut.
  + `PersonsWithRequiredEquipment`— Berbagai orang di mana setiap orang memenuhi kriteria berikut. IDs 
    + Orang tersebut mengenakan semua APD yang ditentukan dalam parameter input `SummarizationAttributes`. 
    + Parameter `Confidence` untuk orang (`ProtectiveEquipmentPerson`), bagian tubuh (`ProtectiveEquipmentBodyPart`), peralatan pelindung (`EquipmentDetection`) sama dengan atau lebih dari ambang batas kepercayaan minimum yang ditentukan (`MinConfidence`).
    + Nilai `CoversBodyPart` untuk semua item APD adalah betul. 
  + `PersonsWithoutRequiredEquipment`— Berbagai orang IDs yang memenuhi salah satu kriteria berikut. 
    + Nilai `Confidence` untuk orang (`ProtectiveEquipmentPerson`), bagian tubuh (`ProtectiveEquipmentBodyPart`), dan cakupan bagian tubuh (`CoversBodyPart`) lebih dari ambang batas minimum yang ditentukan (`MinConfidence`), namun orang tersebut tidak memakai satu atau beberapa APD yang ditentukan (`SummarizationAttributes`).
    + Nilai dari `CoversBodyPart` adalah salah untuk APD tertentu (`SummarizationAttributes`) yang memiliki nilai `Confidence` lebih dari ambang batas kepercayaan minimum yang ditentukan (`MinConfidence`). Orang tersebut juga memiliki semua APD yang ditentukan (`SummarizationAttributes`) dan nilai `Confidence` untuk orang (`ProtectiveEquipmentPerson`), bagian tubuh (`ProtectiveEquipmentBodyPart`), dan peralatan pelindung (`EquipmentDetection`) lebih dari atau sama dengan ambang batas kepercayaan minimum (`MinConfidence`).
  + `PersonsIndeterminate`— Array orang yang IDs terdeteksi di mana `Confidence` nilai untuk orang (`ProtectiveEquipmentPerson`), bagian tubuh (), peralatan pelindung (`EquipmentDetection`), atau `CoversBodyPart` boolean lebih rendah dari ambang kepercayaan minimum yang ditentukan (`MinConfidence`). `ProtectiveEquipmentBodyPart` 

  Gunakan ukuran array untuk mendapatkan hitungan untuk ringkasan tertentu. Misalnya, ukuran `PersonsWithRequiredEquipment` memberi tahu Anda jumlah orang yang terdeteksi memakai tipe APD tertentu.

  Anda dapat menggunakan ID orang untuk mengetahui informasi lebih lanjut tentang seseorang, seperti lokasi kotak pembatas orang tersebut. ID orang memetakan ke bidang ID `ProtectiveEquipmentPerson`) objek yang dikembalikan dalam `Persons` (array `ProtectiveEquipmentPerson`). Anda kemudian bisa mendapatkan kotak pembatas dan informasi lainnya dari objek `ProtectiveEquipmentPerson` yang sesuai. 

```
 {
    "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": []
    }
}
```

# Mendeteksi alat pelindung diri dalam citra
<a name="ppe-procedure-image"></a>

Untuk mendeteksi Alat Pelindung Diri (APD) pada orang dalam citra, gunakan operasi API non-penyimpanan [DetectProtectiveEquipment](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectProtectiveEquipment.html). 

Anda dapat memberikan citra input sebagai array bit citra (bit citra yang dikodekan base64) atau sebagai objek Amazon S3, dengan menggunakan AWS SDK atau AWS Command Line Interface (AWS CLI). Contoh-contoh ini menggunakan citra yang tersimpan di bucket Amazon S3. Untuk informasi selengkapnya, lihat [Bekerja dengan citra](images.md). 

**Untuk mendeteksi APD pada orang dalam citra**

1. Jika belum:

   1. Buat atau perbarui pengguna dengan `AmazonRekognitionFullAccess` dan `AmazonS3ReadOnlyAccess` izin. Untuk informasi selengkapnya, lihat [Langkah 1: Siapkan akun AWS dan buat Pengguna](setting-up.md#setting-up-iam).

   1. Instal dan konfigurasikan AWS CLI dan AWS SDKs. Untuk informasi selengkapnya, lihat [Langkah 2: Mengatur AWS CLI dan AWS SDKs](setup-awscli-sdk.md).

1. Unggah citra (yang berisi satu atau beberapa orang yang memakai APD) ke bucket S3 Anda. 

   Untuk petunjuk, lihat [Mengunggah Objek ke Amazon](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UploadingObjectsintoAmazonS3.html) S3 di Panduan Pengguna *Layanan Penyimpanan Sederhana Amazon*.

1. Gunakan contoh berikut untuk memanggil operasi `DetectProtectiveEquipment`. Untuk informasi tentang menampilkan kotak pembatas di citra, lihat [Menampilkan kotak pembatas](images-displaying-bounding-boxes.md).

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

   Contoh ini menampilkan informasi tentang item APD yang terdeteksi pada orang yang terdeteksi dalam citra. 

   Ubah nilai `amzn-s3-demo-bucket` menjadi nama bucket Amazon S3 yang berisi citra Anda. Ubah nilai `photo` ke nama file citra Anda.

   ```
   //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 ]

   Kode ini diambil dari GitHub repositori contoh SDK AWS Dokumentasi. Lihat contoh lengkapnya [di sini](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 Perintah ini meminta ringkasan APD dan menampilkan output JSON untuk operasi CLI`detect-protective-equipment`. 

   Ubah `amzn-s3-demo-bucket` dengan nama bucket Amazon S3 yang berisi citra. Ubah `input.jpg` menjadi nama citra yang ingin Anda gunakan.

   ```
   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 Perintah ini menampilkan output JSON untuk operasi `detect-protective-equipment` CLI. 

   Ubah `amzn-s3-demo-bucket` dengan nama bucket Amazon S3 yang berisi citra. Ubah `input.jpg` menjadi nama citra yang ingin Anda gunakan.

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

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

   Contoh ini menampilkan informasi tentang item APD yang terdeteksi pada orang yang terdeteksi dalam citra. 

   Ubah nilai `amzn-s3-demo-bucket` menjadi nama bucket Amazon S3 yang berisi citra Anda. Ubah nilai `photo` ke nama file citra Anda. Ganti nilai `profile_name` di baris yang membuat sesi Rekognition dengan nama profil pengembang Anda. 

   ```
   # 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()
   ```

------

# Contoh: Menggambar kotak pembatas di sekitar penutup wajah
<a name="ppe-example-image-bounding-box"></a>

Contoh berikut menunjukkan cara menggambar kotak pembatas di sekitar penutup wajah yang terdeteksi pada orang. Untuk contoh yang menggunakan AWS Lambda dan Amazon DynamoDB, lihat AWS repositori contoh SDK [Documentation](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javav2/usecases/creating_lambda_ppe). GitHub 

Untuk mendeteksi penutup wajah Anda menggunakan operasi API non-penyimpanan [DetectProtectiveEquipment](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectProtectiveEquipment.html). Citra dimuat dari sistem file lokal. Anda memberikan citra input ke `DetectProtectiveEquipment` sebagai array bit citra (bit citra yang dikodekan base64). Untuk informasi selengkapnya, lihat [Bekerja dengan citra](images.md).

Contoh ini menampilkan kotak pembatas di sekitar penutup wajah yang terdeteksi. Kotak pembatas berwarna hijau jika penutup wajah menutupi bagian tubuh sepenuhnya. Jika tidak, kotak pembatas merah ditampilkan. Sebagai peringatan, kotak pembatas kuning ditampilkan dalam kotak pembatas penutup wajah, jika kepercayaan pendeteksian kurang dari nilai kepercayaan yang ditentukan. Jika penutup wajah tidak terdeteksi, maka kotak pembatas merah dicitra di sekitar orang tersebut. 

Output citra tersebut mirip dengan hal berikut. 

![\[Empat pekerja di sebuah gudang, mengenakan rompi visibilitas tinggi, helm, kacamata keselamatan, dan masker. Topeng dikelilingi oleh kotak pembatas.\]](http://docs.aws.amazon.com/id_id/rekognition/latest/dg/images/workers-with-bb.png)


**Untuk menampilkan kotak pembatas pada penutup wajah yang terdeteksi**

1. Jika belum:

   1. Buat atau perbarui pengguna dengan `AmazonRekognitionFullAccess` izin. Untuk informasi selengkapnya, lihat [Langkah 1: Siapkan akun AWS dan buat Pengguna](setting-up.md#setting-up-iam).

   1. Instal dan konfigurasikan AWS CLI dan AWS SDKs. Untuk informasi selengkapnya, lihat [Langkah 2: Mengatur AWS CLI dan AWS SDKs](setup-awscli-sdk.md).

1. Gunakan contoh berikut untuk memanggil operasi `DetectProtectiveEquipment`. Untuk informasi tentang menampilkan kotak pembatas di citra, lihat [Menampilkan kotak pembatas](images-displaying-bounding-boxes.md).

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

   Dalam fungsi `main`, ubah hal berikut: 
   + Nilai `photo` ke jalur dan nama file citra lokal (PNG atau JPEG).
   + Nilai `confidence` sampai dengan tingkat kepercayaan yang diinginkan (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 ]

   Kode ini diambil dari GitHub repositori contoh SDK AWS Dokumentasi. Lihat contoh lengkapnya [di sini](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 ]

   Dalam fungsi `main`, ubah hal berikut: 
   + Nilai `photo` ke jalur dan nama file citra lokal (PNG atau JPEG).
   + Nilai `confidence` sampai dengan tingkat kepercayaan yang diinginkan (50-100).
   +  Ganti nilai `profile_name` di baris yang membuat sesi Rekognition dengan nama profil pengembang Anda. 

   ```
   #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 ]

   Dalam contoh CLI berikut mengubah nilai argumen yang tercantum di bawah ini: 
   + Nilai `photo` ke jalur dan nama file citra lokal (PNG atau JPEG).
   + Nilai `confidence` sampai dengan tingkat kepercayaan yang diinginkan (50-100).
   +  Ganti nilai `profile_name` di baris yang membuat sesi Rekognition dengan nama profil pengembang Anda. 

   ```
                                   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"]}"
   ```

    Jika Anda mengakses CLI pada perangkat Windows, gunakan tanda kutip ganda alih-alih tanda kutip tunggal dan hindari tanda kutip ganda bagian dalam dengan garis miring terbalik (yaitu\$1) untuk mengatasi kesalahan parser yang mungkin Anda temui. Sebagai contoh, lihat berikut ini: 

   ```
                                   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\"]}"
   ```

------