

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

# 保存済み動画分析での作業
<a name="video"></a>

Amazon Rekognition Video は、ビデオの分析に使用できる API です。Amazon Rekognition Video では、Amazon Simple Storage Service (Amazon S3) バケットに保存されているビデオ内のラベル、顔、人物、有名人、およびアダルト (暗示的および明示的) コンテンツを検出できます。Amazon Rekognition Video は、メディア/エンターテインメントや公共安全などのカテゴリで利用できます。これまでのような物体や人物が撮影されたビデオの人間によるスキャンでは、かなりの時間がかかるだけでなく、エラーも頻繁に発生していました。Amazon Rekognition Video を使うことで、ビデオ全体を通しての項目の検出や、項目が登場したタイミングの検出を自動化することができます。

このセクションでは、Amazon Rekognition Video で実行できる分析のタイプ、API の概要、および Amazon Rekognition Video の使用例について説明します。

**Topics**
+ [分析のタイプ](#video-recognition-types)
+ [Amazon Rekognition Video API の概要](#video-api-overview)
+ [Amazon Rekognition Video オペレーションを呼び出す](api-video.md)
+ [Amazon Rekognition Video の設定](api-video-roles.md)
+ [Java または Python を使用した、Amazon S3 バケットに保存されたビデオの分析 (SDK)](video-analyzing-with-sqs.md)
+ [を使用したビデオの分析 AWS Command Line Interface](video-cli-commands.md)
+ [リファレンス: ビデオ分析結果の通知](video-notification-payload.md)
+ [Amazon Rekognition Video のトラブルシューティング](video-troubleshooting.md)

## 分析のタイプ
<a name="video-recognition-types"></a>

Amazon Rekognition Video を使用して、以下の情報についてビデオを分析できます。
+ [ビデオセグメント](segments.md)
+ [ラベル](labels.md)
+ [暗示的および明示的なアダルトコンテンツ](moderation.md)
+ [[テキスト]](text-detection.md)
+ [有名人](celebrities.md)
+ [顔](faces.md)
+ [人員](persons.md)

詳細については、「[Amazon Rekognition の仕組み](how-it-works.md)」を参照してください。

## Amazon Rekognition Video API の概要
<a name="video-api-overview"></a>

Amazon Rekognition Video は、Amazon S3 バケットに保存されたビデオを処理します。その設計パターンは、複数のオペレーションの非同期セットとなっており、[StartLabelDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartLabelDetection.html) などの `Start` オペレーションを呼び出すと、ビデオの分析が開始されます。リクエストの完了ステータスは、Amazon Simple Notification Service (Amazon SNS) トピックに発行されます。Amazon SNS トピックから完了ステータスを取得するには、Amazon Simple Queue Service (Amazon SQS) キューまたは AWS Lambda 関数を使用できます。完了ステータスを取得したら、[GetLabelDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GetLabelDetection.html) などの `Get` オペレーションを呼び出してリクエストの結果を取得します。

次の図表は、Amazon S3 バケットに保存されているビデオ内のラベルを検出するプロセスを示しています。この図では、Amazon SQS キューが Amazon SNS トピックから完了ステータスを取得しています。または、 AWS Lambda 関数を使用することもできます。

![\[Amazon Rekognition Video、Amazon SNS、Amazon SQS を使用したビデオ分析の手順を示すフロー図。StartLabelDetection、GetLabelDetection ジョブ、各キューへの完了ステータスの発行などのコンポーネントが含まれている。\]](http://docs.aws.amazon.com/ja_jp/rekognition/latest/dg/images/VideoRekognition.png)


このプロセスは、他の Amazon Rekognition Video オペレーションでも同じです。以下の表は、非ストレージの各 Amazon Rekognition オペレーションの `Start` オペレーションと `Get` オペレーションを一覧したものです。


| 検出 | Start オペレーション | Get オペレーション | 
| --- | --- | --- | 
|  ビデオセグメント  |  [StartSegmentDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartSegmentDetection.html)  |  [GetSegmentDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GetSegmentDetection.html)  | 
|  ラベル  |  [StartLabelDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartLabelDetection.html)  |  [GetLabelDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GetLabelDetection.html)  | 
|  明示的および暗示的なアダルトコンテンツ  |  [StartContentModeration](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartContentModeration.html)  |  [GetContentModeration](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GetContentModeration.html)  | 
|  テキスト  |  [StartTextDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartTextDetection.html)  |  [GetTextDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GetTextDetection.html)  | 
|  有名人  |  [StartCelebrityRecognition](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartCelebrityRecognition.html)  |  [GetCelebrityRecognition](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GetCelebrityRecognition.html)  | 
|  顔  |  [StartFaceDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartFaceDetection.html)  |  [GetFaceDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GetFaceDetection.html)  | 
|  People  |  [StartPersonTracking](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartPersonTracking.html)  |  [GetPersonTracking](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GetPersonTracking.html)  | 

`Get` 以外の `GetCelebrityRecognition` オペレーションの場合、Amazon Rekognition Video は入力ビデオ全体でエンティティ検出時の追跡情報を返します。

Amazon Rekognition Video の使用の詳細については、[Amazon Rekognition Video オペレーションを呼び出す](api-video.md) を参照してください。Amazon SQS を使用してビデオ分析を行う例については、[Java または Python を使用した、Amazon S3 バケットに保存されたビデオの分析 (SDK)](video-analyzing-with-sqs.md) を参照してください。 AWS CLI 例については、「」を参照してください[を使用したビデオの分析 AWS Command Line Interface](video-cli-commands.md)。

### ビデオの形式とストレージ
<a name="video-storage-formats"></a>

Amazon Rekognition のオペレーションでは、Amazon S3 バケットに保存されているビデオを分析できます。ビデオ分析オペレーションの全制限のリストについては、「[Amazon Rekognition のガイドラインとクォータ](limits.md)」を参照してください。

ビデオは H.264 コーデックでエンコードする必要があります。サポートされているファイル形式は MPEG-4 および MOV です。

コーデックとは、データ圧縮による高速な配信と、受信データからオリジナル形式への解凍を可能にするソフトウェアまたはハードウェアです。H.264 コーデックは、ビデオコンテンツの記録、圧縮、配信に広く使われています。1 つのビデオ形式には 1 つ以上のコーデックを含めることができます。MOV または MPEG-4 形式のビデオファイルが Amazon Rekognition Video で動作しない場合、H.264 コーデックがビデオのエンコードに使われているかどうかを確認してください。

オーディオデータを分析する Amazon Rekognition Video API は、AAC オーディオコーデックのみをサポートします。

保存済みビデオの最大ファイルサイズは 10 GB です。

### 人物の検索
<a name="video-searching-persons-overview"></a>

コレクションに保存された顔のメタデータを使ってビデオ内の人物を検索できます。例えば、アーカイブされたビデオから特定の人物や複数の人物を検索できます。[IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html) オペレーションを使用して、ソースイメージの顔のメタデータをコレクションに保存します。次に [StartFaceSearch](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartFaceSearch.html) を使用して、コレクション内の顔の検索を非同期で開始します。検索結果の取得には、[GetFaceSearch](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GeFaceSearch.html) を使用します。詳細については、「[保存したビデオでの顔の検索](procedure-person-search-videos.md)」を参照してください。人物の検索は、代表的なストレージベースの Amazon Rekognition オペレーションです。詳細については、「[ストレージ型 API オペレーション](how-it-works-storage-non-storage.md#how-it-works-storage-based)」を参照してください。

ストリーミングビデオ内の人物を検索することもできます。詳細については、「[ストリーミングビデオイベントの操作](streaming-video.md)」を参照してください。

# Amazon Rekognition Video オペレーションを呼び出す
<a name="api-video"></a>

Amazon Rekognition Video は、Amazon Simple Storage Service (Amazon S3) バケットに保存されているビデオの分析に使用できる非同期 API です。[StartPersonTracking](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartPersonTracking.html) などの Amazon Rekognition Video の `Start` オペレーションを呼び出して、ビデオの分析を開始します。Amazon Rekognition Video は、分析リクエストの完了ステータスを Amazon Simple Notification Service (Amazon SNS) トピックに発行します。Amazon Simple Queue Service (Amazon SQS) キューまたは AWS Lambda 関数を使用して、Amazon SNS トピックからビデオ分析リクエストの完了ステータスを取得できます。最後に、[GetPersonTracking](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GetPersonTracking.html) などの Amazon Rekognition `Get` オペレーションを呼び出して、ビデオ分析リクエストの結果を取得します。

以下のセクションでは、ラベル検出オペレーションを使用して、Amazon S3 バケットに保存されているビデオ内のラベル (オブジェクト、イベント、概念、およびアクティビティ) を Amazon Rekognition Video が検出する方法を説明します。この方法は、他の Amazon Rekognition Video オペレーション ([StartFaceDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartFaceDetection.html) や [StartPersonTracking](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartPersonTracking.html)) でも同様に機能します。この例 [Java または Python を使用した、Amazon S3 バケットに保存されたビデオの分析 (SDK)](video-analyzing-with-sqs.md) では、Amazon SQS キューを使用して、Amazon SNS トピックから完了ステータスを取得し、ビデオを分析する方法を説明しています。また、[人物の動線の検出](persons.md) など、他の Amazon Rekognition Video の例のベースとして使用することもできます。 AWS CLI 例については、「」を参照してください[を使用したビデオの分析 AWS Command Line Interface](video-cli-commands.md)。

**Topics**
+ [ビデオ分析のスタート](#api-video-start)
+ [Amazon Rekognition Video 分析リクエストの完了ステータスの取得](#api-video-get-status)
+ [Amazon Rekognition Video の分析結果を取得する](#api-video-get)

## ビデオ分析のスタート
<a name="api-video-start"></a>

[StartLabelDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartLabelDetection.html) を呼び出して、Amazon Rekognition Video のラベル検出リクエストを開始します。以下は、`StartLabelDetection` により渡される JSON リクエストの例を示しています。

```
{
    "Video": {
        "S3Object": {
            "Bucket": "amzn-s3-demo-bucket",
            "Name": "video.mp4"
        }
    },
    "ClientRequestToken": "LabelDetectionToken",
    "MinConfidence": 50,
    "NotificationChannel": {
        "SNSTopicArn": "arn:aws:sns:us-east-1:nnnnnnnnnn:topic",
        "RoleArn": "arn:aws:iam::nnnnnnnnnn:role/roleopic"
    },
    "JobTag": "DetectingLabels"
}
```

入力パラメータ `Video` はビデオファイル名を提供し、`NotificationChannel` から取得する Amazon S3 バケットには、ビデオ分析リクエストが終了したときに Amazon Rekognition Video が通知する Amazon SNS トピックの Amazon リソースネーム (ARN) が含まれます。Amazon SNS トピックは、呼び出し先の エンドポイントと同じ AWS リージョン内に存在する必要があります。`NotificationChannel` には、Amazon Rekognition Video に Amazon SNS トピックの発行を許可するためのロールの ARN も含まれています。IAM サービスロールを作成して、Amazon Rekognition に Amazon SNS トピックへの発行許可を付与します。詳細については、「[Amazon Rekognition Video の設定](api-video-roles.md)」を参照してください。

`JobTag` というオプションの入力パラメータを指定して、Amazon SNS トピックに発行された完了ステータスのジョブを特定することもできます。

`ClientRequestToken` というべき等トークンをオプションで設定すると、分析ジョブが誤って重複するのを防ぐことができます。`ClientRequestToken` の値を指定すると、`Start` オペレーションは、`StartLabelDetection` などの Start オペレーションに対する複数かつ同一の呼び出しに共通する `JobId` を返します。`ClientRequestToken` トークンの有効期間は 7 日です。7 日後に再利用することができます。トークンの有効期間中にトークンを再利用すると、以下のことが発生します。
+ 同じ `Start` オペレーション、同じ入力パラメータでトークンを再利用すると、同じ `JobId` が返されます。ジョブは再度実行されず、Amazon Rekognition Video は、登録されている Amazon SNS トピックに完了ステータスを送信しません。
+ 同じ `Start` オペレーションで、入力パラメータを少し変更してトークンを再利用すると、`IdempotentParameterMismatchException` (HTTP ステータスコード: 400) 例外を受け取ります。
+ Amazon Rekognition から予期しない結果が発生する可能性があるため、トークンを異なる `Start` オペレーションで再利用しないでください。

`StartLabelDetection` オペレーションに対する応答は、ジョブ識別子 (`JobId`) です。Amazon Rekognition Video が完了ステータスを Amazon SNS トピックに発行したら、`JobId` を使用してリクエストを追跡し、分析結果を取得します。例: 

```
{"JobId":"270c1cc5e1d0ea2fbc59d97cb69a72a5495da75851976b14a1784ca90fc180e3"}
```

同時に開始するジョブが多すぎると、`StartLabelDetection` の呼び出しによって、同時に実行されるジョブの数が Amazon Rekognition サービスの制限を下回るまで `LimitExceededException` (HTTP ステータスコード: 400)が発生します。

アクティビティのバーストにより `LimitExceededException` 例外が発生した場合は、 Amazon SQS キューを使用して受信リクエストを管理することを検討してください。同時リクエストの平均数が Amazon SQS キューで管理できず、まだ`LimitExceededException`例外が発生している場合は、 AWS サポートにお問い合わせください。

## Amazon Rekognition Video 分析リクエストの完了ステータスの取得
<a name="api-video-get-status"></a>

Amazon Rekognition Video は、登録されている Amazon SNS トピックに分析完了の通知を送信します。通知には、ジョブ識別子およびオペレーション完了ステータスが JSON 文字列で含まれています。ビデオ分析リクエストが正常に実行された場合は `SUCCEEDED` ステータスとなります。例えば、次の結果はラベル検出ジョブが正常に処理されたことを示しています。

```
{
    "JobId": "270c1cc5e1d0ea2fbc59d97cb69a72a5495da75851976b14a1nnnnnnnnnnnn",
    "Status": "SUCCEEDED",
    "API": "StartLabelDetection",
    "JobTag": "DetectingLabels",
    "Timestamp": 1510865364756,
    "Video": {
        "S3ObjectName": "video.mp4",
        "S3Bucket": "amzn-s3-demo-bucket"
    }
}
```

詳細については、「[リファレンス: ビデオ分析結果の通知](video-notification-payload.md)」を参照してください。

Amazon Rekognition Video が Amazon SNS トピックに発行したステータス情報を取得するには、次のいずれかのオプションを使用します。
+ **AWS Lambda** – Amazon SNS トピックに書き込む AWS Lambda 関数をサブスクライブできます。この関数は、Amazon Rekognition によってリクエスト完了が Amazon SNS トピックに通知されると呼び出されます。ビデオ分析リクエストの結果をサーバー側のコードで処理する場合は Lambda 関数を使用します。例えば、クライアントアプリケーションに情報を返す前に、ビデオに注釈を付けたり、ビデオコンテンツに関するレポートを作成したりする場合があります。また、Amazon Rekognition API が大量のデータを返す可能性があるため、ビデオの容量が大きい場合もサーバー側での処理をお勧めします。
+ [**Amazon Simple Queue Service**]— Amazon SQS キューを Amazon SNS トピックにサブスクライブできます。次にこの Amazon SQS キューをポーリングすることで、リクエストの完了時に Amazon Rekognition によって発行される完了ステータスを取得できます。詳細については、「[Java または Python を使用した、Amazon S3 バケットに保存されたビデオの分析 (SDK)](video-analyzing-with-sqs.md)」を参照してください。Amazon SQS キューは、Amazon Rekognition Video のオペレーションをクライアントアプリケーションからのみ呼び出す場合に使用します。

**重要**  
リクエストの完了ステータスを取得するために、Amazon Rekognition Video の `Get` オペレーションを繰り返し呼び出すことは推奨されません。これは、実行されるリクエストが多すぎると、Amazon Rekognition Videoによる `Get` オペレーションの調整が行われるためです。複数のビデオを同時処理する場合は、Amazon Rekognition Video をポーリングして各ビデオのステータスを個別に取得するよりも、1 つの SQS キューの完了通知をモニタリングするほうがシンプルかつ効率的です。

## Amazon Rekognition Video の分析結果を取得する
<a name="api-video-get"></a>

 ビデオ分析リクエストの結果を取得するには、まず Amazon SNS トピックから取得された完了ステータスが `SUCCEEDED` であることを確認します。次に `GetLabelDetection` を呼び出し、`StartLabelDetection` から返された `JobId` の値を渡します。リクエストの JSON は次の例のようになります。

```
{
    "JobId": "270c1cc5e1d0ea2fbc59d97cb69a72a5495da75851976b14a1784ca90fc180e3",
    "MaxResults": 10,
    "SortBy": "TIMESTAMP"
}
```

JobId はビデオ分析オペレーションの識別子です。ビデオの分析で大量のデータが生成される場合に備えて、1 回の Get オペレーションで返される結果の最大数を `MaxResults` で指定できます。`MaxResults` のデフォルト値は 1000 です。1000 より大きい値を指定した場合、最大 1000 件の結果が返されます。オペレーションが結果セット全体を返さない場合、次のページ用のページ分割トークンがオペレーションの応答で返されます。直前の Get リクエストでページ分割トークンが返された場合は、そのトークンと `NextToken` を使って次の結果ページを取得できます。

**注記**  
Amazon Rekognition はビデオ分析オペレーションの結果を 7 日間保持します。この期間を過ぎると分析結果を取得できなくなります。

`GetLabelDetection` オペレーションの応答の JSON は次のようになります。

```
{
    "Labels": [
        {
            "Timestamp": 0,
            "Label": {
                "Instances": [],
                "Confidence": 60.51791763305664,
                "Parents": [],
                "Name": "Electronics"
            }
        },
        {
            "Timestamp": 0,
            "Label": {
                "Instances": [],
                "Confidence": 99.53411102294922,
                "Parents": [],
                "Name": "Human"
            }
        },
        {
            "Timestamp": 0,
            "Label": {
                "Instances": [
                    {
                        "BoundingBox": {
                            "Width": 0.11109819263219833,
                            "Top": 0.08098889887332916,
                            "Left": 0.8881205320358276,
                            "Height": 0.9073750972747803
                        },
                        "Confidence": 99.5831298828125
                    },
                    {
                        "BoundingBox": {
                            "Width": 0.1268676072359085,
                            "Top": 0.14018426835536957,
                            "Left": 0.0003282368124928324,
                            "Height": 0.7993982434272766
                        },
                        "Confidence": 99.46029663085938
                    }
                ],
                "Confidence": 99.53411102294922,
                "Parents": [],
                "Name": "Person"
            }
        },
        .
        .   
        .

        {
            "Timestamp": 166,
            "Label": {
                "Instances": [],
                "Confidence": 73.6471176147461,
                "Parents": [
                    {
                        "Name": "Clothing"
                    }
                ],
                "Name": "Sleeve"
            }
        }
        
    ],
    "LabelModelVersion": "2.0",
    "JobStatus": "SUCCEEDED",
    "VideoMetadata": {
        "Format": "QuickTime / MOV",
        "FrameRate": 23.976024627685547,
        "Codec": "h264",
        "DurationMillis": 5005,
        "FrameHeight": 674,
        "FrameWidth": 1280
    }
}
```

`GetLabelDetection` および `GetContentModeration` オペレーションでは、分析結果をタイムスタンプまたはラベル名でソートできます。また、結果をビデオセグメント別またはタイムスタンプ別に集計することもできます。

結果は、検出時間 (ビデオの開始時間からミリ秒単位) または検出されたエンティティ (オブジェクト、顔、有名人、モデレーションラベル、人物) のアルファベット順で並べ替えることができます。時間で並べ替える場合は、`SortBy` 入力パラメータの値を `TIMESTAMP` に設定します。`SortBy` が指定されていない場合のデフォルトの動作は、時間による並べ替えです。上記の例は時間で並べ替えられています。エンティティで並べ替えるには、実行するオペレーションにとって適切な値を `SortBy` 入力パラメータで使用します。例えば、`GetLabelDetection` への呼び出しで検出されたラベルで並べ替える、`NAME` 値を使用します。

結果をタイムスタンプ別に集計するには、`AggregateBy` パラメータの値を `TIMESTAMPS` に設定します。ビデオセグメントでは、`AggregateBy` の値を `SEGMENTS` に設定します。`SEGMENTS` 集計モードは、ラベルを経時的に集計し、`TIMESTAMPS` は、2 FPS サンプリングとフレームごとの出力を使って、ラベルが検出されたタイムスタンプを表示します (注: 現在のサンプリングレートは変更される可能性があるため、現在のサンプリングレートを基に予測しないようにしてください)。値が指定されていない場合、デフォルトの集計方法は `TIMESTAMPS` です。

# Amazon Rekognition Video の設定
<a name="api-video-roles"></a>

保存したビデオで Amazon Rekognition Video API を使用するには、Amazon SNS トピックにアクセスできるようにユーザーと IAM サービスロールを設定する必要があります。また、Amazon SQS キューを Amazon SNS トピックにサブスクライブする必要があります。

**注記**  
これらの手順を使用して [Java または Python を使用した、Amazon S3 バケットに保存されたビデオの分析 (SDK)](video-analyzing-with-sqs.md) の例を設定する場合は、ステップ 3、4、5、6 を実行する必要はありません。この例には、Amazon SNS トピックと Amazon SQS キューを作成して設定するコードが含まれています。

このセクションの例では、Amazon Rekognition Video が複数のトピックにアクセスできるようにする手順を使用して、新しい Amazon SNS トピックを作成します。既存の Amazon SNS トピックを使用する場合は、ステップ 3 の [既存の Amazon SNS トピックへのアクセスをataeruする](#api-video-roles-single-topics) を使用します。<a name="configure-rekvid-procedure"></a>

**Amazon Rekognition Video を設定するには**

1. Amazon Rekognition Video にアクセスする AWS ようにアカウントを設定します。詳細については、「[ステップ 1: AWS アカウントを設定してユーザーを作成する](setting-up.md)」を参照してください。

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

1. このデベロッパーガイドのコード例を実行するには、選択したユーザーがプログラムによるアクセス権限を持っていることを確認してください。詳細については「[プログラマチックアクセス権を付与する](sdk-programmatic-access.md)」を参照してください。

   また、ユーザーには少なくとも以下の権限が必要です。
   + AmazonSQSFullAccess
   + AmazonRekognitionFullAccess
   + AmazonS3FullAccess
   + AmazonSNSFullAccess

   IAM アイデンティティセンターを使用して認証を行う場合は、ロールの許可セットにアクセス権限を追加し、それ以外の場合は IAM ロールにアクセス権限を追加します。

1. [[Amazon SNS コンソール](https://console.aws.amazon.com/sns/v2/home)] を使用して [[Amazon SNS トピック](https://docs.aws.amazon.com/sns/latest/dg/CreateTopic.html)] を作成します。トピック名の先頭に *AmazonRekognition* を追加します。その Amazon リソースネーム (ARN) をメモします。このトピックが、使用している AWS エンドポイントと同じリージョンにあることを確認します。

1. [[Amazon SQS コンソール](https://console.aws.amazon.com/sqs/)] を使用して、[[Amazon SQS スタンダードキュー](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-create-queue.html)] を作成します。キューの ARN を書き留めます。

1. ステップ 3 で作成した[トピックにキューをサブスクライブ](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-subscribe-queue-sns-topic.html)します。

1. [[Amazon SNS トピックに、Amazon SQS キューへメッセージを送信する許可を与えます](https://docs.aws.amazon.com/sns/latest/dg/SendMessageToSQS.html#SendMessageToSQS.sqs.permissions)]。

1. IAM サービスロールを作成して、Amazon Rekognition Video に Amazon SNS トピックへのアクセスを許可します。このサービスロールの Amazon リソースネーム (ARN) をメモします。詳細については、「[複数の Amazon SNS トピックへのアクセスを許可する](#api-video-roles-all-topics)」を参照してください。

1. アカウントの安全を確保するには、Rekognition のアクセス範囲を、使用しているリソースのみに制限する必要があります。これは、IAM サービスロールに信頼ポリシーをアタッチすることで実行できます。これを行う方法については、「[サービス間の混乱した代理の防止](cross-service-confused-deputy-prevention.md)」を参照してください。

1. ステップ 1 で作成したユーザーに[次のインラインポリシーを追加します](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html#embed-inline-policy-console)。

   インラインポリシーに任意の名前を付けます。

1. カスタマーマネージド AWS Key Management Service キーを使用して Amazon S3 バケット内の動画を暗号化する場合は、ステップ 7 で作成したサービスロールに動画の復号を許可するアクセス許可をキー[に追加](https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-modifying.html#key-policy-modifying-how-to-console-policy-view)します。サービスロールには少なくとも、`kms:GenerateDataKey` および `kms:Decrypt` アクションのアクセス権限が必要です。例えば、次のようになります。

   ```
   {
       "Sid": "Decrypt only",
       "Effect": "Allow",
       "Principal": {
           "AWS": "arn:aws:iam::111122223333:user/user from step 1"
       },
       "Action": [
           "kms:Decrypt",
           "kms:GenerateDataKey"
       ],
       "Resource": "*"
   }
   ```

   詳細については、「[私の Amazon S3 バケットにはカスタムの AWS KMS キーを使用したデフォルト暗号化が設定されています。ユーザーがそのバケットでダウンロードやアップロードを行えるようにするにはどうすればいいですか?](https://aws.amazon.com/premiumsupport/knowledge-center/s3-bucket-access-default-encryption/)」および「[Protecting Data Using Server-Side Encryption with KMS keys Stored in AWS Key Management Service (SSE-KMS)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html)」を参照してください。

1. これで、「[Java または Python を使用した、Amazon S3 バケットに保存されたビデオの分析 (SDK)](video-analyzing-with-sqs.md)」と「[を使用したビデオの分析 AWS Command Line Interface](video-cli-commands.md)」の例を実行できます。

## 複数の Amazon SNS トピックへのアクセスを許可する
<a name="api-video-roles-all-topics"></a>

IAM サービスロールを使用し、作成したAmazon SNS トピックへのアクセスを Amazon Rekognition Video に付与します。IAM は、Amazon Rekognition Video サービスロール作成用の [*Rekognition*] ユースケースを提供します。

Amazon Rekognition Videoは、`AmazonRekognitionServiceRole` 許可ポリシーを使用し、トピック名の前に [*AmazonRekognition*] を付けることで、複数の Amazon SNS トピックへのアクセスを与えることができます (例: `AmazonRekognitionMyTopicName`)。

**Amazon Rekognition Video を複数の Amazon SNS トピックにアクセスできるようにするには**

1. [[IAM サービスロールを作成します](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html?icmpid=docs_iam_console)]。次の情報を使用して、IAM サービスロールを作成します。

   1. サービス名の **Rekognition** を選択します。

   1. サービスロールのユースケースの **Rekognition** を選択します。**AmazonRekognitionServiceRole** アクセス権限ポリシーが表示されます。[**AmazonRekognitionServiceRole**] は、[*AmazonRekognition*] をプレフィックスとする Amazon SNS トピックへのアクセス権を Amazon Rekognition Video に付与します。

   1. サービスロールに任意の名前を付けます。

1. サービスロールの ARN をメモしておきます。これは、ビデオ分析のオペレーションを開始する際に必要です。

## 既存の Amazon SNS トピックへのアクセスをataeruする
<a name="api-video-roles-single-topics"></a>

既存の Amazon SNS トピックへのアクセスを Amazon Rekognition Video に付与するアクセス許可ポリシーを作成できます。

**Amazon Rekognition Video を Amazon SNS トピックにアクセスできるようにするには**

1. [[IAM JSON ポリシーエディターを使用して新しい許可ポリシーを作成し](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html#access_policies_create-json-editor)]、次のポリシーを使用します。`topicarn` を、目的の Amazon SNS トピックの Amazon リソースネーム (ARN) に置き換えます。

1. [IAM サービスロールを作成する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html?icmpid=docs_iam_console) または、既存の IAM サービスロールを更新します。次の情報を使用して、IAM サービスロールを作成します。

   1. サービス名の **Rekognition** を選択します。

   1. サービスロールのユースケースの **Rekognition** を選択します。

   1. 手順 1 で作成したアクセス権ポリシーを添付します。

1. サービスロールの ARN をメモしておきます。これは、ビデオ分析のオペレーションを開始する際に必要です。

# Java または Python を使用した、Amazon S3 バケットに保存されたビデオの分析 (SDK)
<a name="video-analyzing-with-sqs"></a>

この手順では、Amazon Rekognition Video ラベル検出オペレーション、Amazon S3 バケットに保存さされたビデオ、および Amazon SNS トピックを使用して、ビデオ内のラベルを検出する方法について説明します。また、Amazon SQS キューを使用して Amazon SNS トピックから完了ステータスを取得する方法についても説明します。詳細については、「[Amazon Rekognition Video オペレーションを呼び出す](api-video.md)」を参照してください。Amazon SQS キューの使用に制限されるわけではありません。たとえば、 AWS Lambda 関数を使用して完了ステータスを取得できます。詳細については、「[Amazon SNS 通知を使用した Lambda 関数の呼び出し](https://docs.aws.amazon.com/sns/latest/dg/sns-lambda.html)」を参照してください。

手順に含まれているコード例は、以下を実行する方法を示しています。

1. Amazon SNS トピックを作成します。

1. Amazon SQS キュー を作成します。

1. Amazon Rekognition Video に、ビデオ分析オペレーションの完了ステータスを Amazon SNS トピックに発行するアクセス許可を与えます。

1. Amazon SQS キューを Amazon SNS トピックへサブスクライブします。

1. [StartLabelDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartLabelDetection.html) を呼び出してビデオ分析リクエストを開始します。

1. 完了ステータスを Amazon SQS キューから取得します。この例では、`StartLabelDetection` で返されたジョブ識別子 (`JobId`) を追跡し、一致するジョブ識別子の結果だけを完了ステータスから読み取ります。他のアプリケーションで同じキューやトピックを使用している場合、この点を考慮することが重要です。わかりやすいように、この例では一致しないジョブが削除されます。これらを Amazon SQS デッドレターキューに追加して詳しく調査することを検討してください。

1. [GetLabelDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GetLabelDetection.html) を呼び出して、ビデオ分析結果を取得し表示します。

## 前提条件
<a name="video-prerequisites"></a>

この手順のコード例は Java と Python で提供されています。適切な AWS SDK をインストールする必要があります。詳細については、「[Amazon Rekognition の開始方法](getting-started.md)」を参照してください。使用する AWS アカウントには、Amazon Rekognition API に対するアクセス許可が必要です。詳細については、[[Amazon Rekognition で定義されるアクション](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonrekognition.html#amazonrekognition-actions-as-permissions)] を参照してください。

**ビデオ内のラベルを検出するには**

1. Amazon Rekognition Video へのユーザーアクセスを設定し、Amazon SNS への Amazon Rekognition Video アクセスを設定します。詳細については、「[Amazon Rekognition Video の設定](api-video-roles.md)」を参照してください。コード例によって Amazon SNS トピックと Amazon SQS キューが作成されて設定されるため、ステップ 3、4、5、6 を実行する必要はありません。

1. Amazon S3 バケットに MOV または MPEG- 4 形式のビデオファイルをアップロードします。テストの場合、長さが 30 秒以内のビデオをアップロードしてください。

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

   

1. 次のコード例を使用して、ビデオ内のラベルを検出します。

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

   `main` 関数内:
   + `roleArn` を、[Amazon Rekognition Video を設定するには](api-video-roles.md#configure-rekvid-procedure) のステップ 7 で作成した IAM サービスロールの ARN に置き換えます。
   + `amzn-s3-demo-bucket` と `video` の値を、ステップ 2 で指定したバケット名とビデオファイル名に置き換えます。

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   package com.amazonaws.samples;
   import com.amazonaws.auth.policy.Policy;
   import com.amazonaws.auth.policy.Condition;
   import com.amazonaws.auth.policy.Principal;
   import com.amazonaws.auth.policy.Resource;
   import com.amazonaws.auth.policy.Statement;
   import com.amazonaws.auth.policy.Statement.Effect;
   import com.amazonaws.auth.policy.actions.SQSActions;
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.amazonaws.services.rekognition.model.CelebrityDetail;
   import com.amazonaws.services.rekognition.model.CelebrityRecognition;
   import com.amazonaws.services.rekognition.model.CelebrityRecognitionSortBy;
   import com.amazonaws.services.rekognition.model.ContentModerationDetection;
   import com.amazonaws.services.rekognition.model.ContentModerationSortBy;
   import com.amazonaws.services.rekognition.model.Face;
   import com.amazonaws.services.rekognition.model.FaceDetection;
   import com.amazonaws.services.rekognition.model.FaceMatch;
   import com.amazonaws.services.rekognition.model.FaceSearchSortBy;
   import com.amazonaws.services.rekognition.model.GetCelebrityRecognitionRequest;
   import com.amazonaws.services.rekognition.model.GetCelebrityRecognitionResult;
   import com.amazonaws.services.rekognition.model.GetContentModerationRequest;
   import com.amazonaws.services.rekognition.model.GetContentModerationResult;
   import com.amazonaws.services.rekognition.model.GetFaceDetectionRequest;
   import com.amazonaws.services.rekognition.model.GetFaceDetectionResult;
   import com.amazonaws.services.rekognition.model.GetFaceSearchRequest;
   import com.amazonaws.services.rekognition.model.GetFaceSearchResult;
   import com.amazonaws.services.rekognition.model.GetLabelDetectionRequest;
   import com.amazonaws.services.rekognition.model.GetLabelDetectionResult;
   import com.amazonaws.services.rekognition.model.GetPersonTrackingRequest;
   import com.amazonaws.services.rekognition.model.GetPersonTrackingResult;
   import com.amazonaws.services.rekognition.model.Instance;
   import com.amazonaws.services.rekognition.model.Label;
   import com.amazonaws.services.rekognition.model.LabelDetection;
   import com.amazonaws.services.rekognition.model.LabelDetectionSortBy;
   import com.amazonaws.services.rekognition.model.NotificationChannel;
   import com.amazonaws.services.rekognition.model.Parent;
   import com.amazonaws.services.rekognition.model.PersonDetection;
   import com.amazonaws.services.rekognition.model.PersonMatch;
   import com.amazonaws.services.rekognition.model.PersonTrackingSortBy;
   import com.amazonaws.services.rekognition.model.S3Object;
   import com.amazonaws.services.rekognition.model.StartCelebrityRecognitionRequest;
   import com.amazonaws.services.rekognition.model.StartCelebrityRecognitionResult;
   import com.amazonaws.services.rekognition.model.StartContentModerationRequest;
   import com.amazonaws.services.rekognition.model.StartContentModerationResult;
   import com.amazonaws.services.rekognition.model.StartFaceDetectionRequest;
   import com.amazonaws.services.rekognition.model.StartFaceDetectionResult;
   import com.amazonaws.services.rekognition.model.StartFaceSearchRequest;
   import com.amazonaws.services.rekognition.model.StartFaceSearchResult;
   import com.amazonaws.services.rekognition.model.StartLabelDetectionRequest;
   import com.amazonaws.services.rekognition.model.StartLabelDetectionResult;
   import com.amazonaws.services.rekognition.model.StartPersonTrackingRequest;
   import com.amazonaws.services.rekognition.model.StartPersonTrackingResult;
   import com.amazonaws.services.rekognition.model.Video;
   import com.amazonaws.services.rekognition.model.VideoMetadata;
   import com.amazonaws.services.sns.AmazonSNS;
   import com.amazonaws.services.sns.AmazonSNSClientBuilder;
   import com.amazonaws.services.sns.model.CreateTopicRequest;
   import com.amazonaws.services.sns.model.CreateTopicResult;
   import com.amazonaws.services.sqs.AmazonSQS;
   import com.amazonaws.services.sqs.AmazonSQSClientBuilder;
   import com.amazonaws.services.sqs.model.CreateQueueRequest;
   import com.amazonaws.services.sqs.model.Message;
   import com.amazonaws.services.sqs.model.QueueAttributeName;
   import com.amazonaws.services.sqs.model.SetQueueAttributesRequest;
   import com.fasterxml.jackson.databind.JsonNode;
   import com.fasterxml.jackson.databind.ObjectMapper;
   import java.util.*;
   
   public class VideoDetect {
    
       
       private static String sqsQueueName=null;
       private static String snsTopicName=null;
       private static String snsTopicArn = null;
       private static String roleArn= null;
       private static String sqsQueueUrl = null;
       private static String sqsQueueArn = null;
       private static String startJobId = null;
       private static String bucket = null;
       private static String video = null; 
       private static AmazonSQS sqs=null;
       private static AmazonSNS sns=null;
       private static AmazonRekognition rek = null;
       
       private static NotificationChannel channel= new NotificationChannel()
               .withSNSTopicArn(snsTopicArn)
               .withRoleArn(roleArn);
   
   
       public static void main(String[] args) throws Exception {
           
           video = "";
           bucket = "";
           roleArn= "";
   
           sns = AmazonSNSClientBuilder.defaultClient();
           sqs= AmazonSQSClientBuilder.defaultClient();
           rek = AmazonRekognitionClientBuilder.defaultClient();
     
           CreateTopicandQueue();
           
           //=================================================
           
           StartLabelDetection(bucket, video);
   
           if (GetSQSMessageSuccess()==true)
           	GetLabelDetectionResults();
           
          //=================================================  
           
   
           DeleteTopicandQueue();
           System.out.println("Done!");
          
       }
   
       
       static boolean GetSQSMessageSuccess() throws Exception
       {
       	boolean success=false;
   
      
           System.out.println("Waiting for job: " + startJobId);
           //Poll queue for messages
           List<Message> messages=null;
           int dotLine=0;
           boolean jobFound=false;
   
           //loop until the job status is published. Ignore other messages in queue.
           do{
               messages = sqs.receiveMessage(sqsQueueUrl).getMessages();
               if (dotLine++<40){
                   System.out.print(".");
               }else{
                   System.out.println();
                   dotLine=0;
               }
   
               if (!messages.isEmpty()) {
                   //Loop through messages received.
                   for (Message message: messages) {
                       String notification = message.getBody();
   
                       // Get status and job id from notification.
                       ObjectMapper mapper = new ObjectMapper();
                       JsonNode jsonMessageTree = mapper.readTree(notification);
                       JsonNode messageBodyText = jsonMessageTree.get("Message");
                       ObjectMapper operationResultMapper = new ObjectMapper();
                       JsonNode jsonResultTree = operationResultMapper.readTree(messageBodyText.textValue());
                       JsonNode operationJobId = jsonResultTree.get("JobId");
                       JsonNode operationStatus = jsonResultTree.get("Status");
                       System.out.println("Job found was " + operationJobId);
                       // Found job. Get the results and display.
                       if(operationJobId.asText().equals(startJobId)){
                           jobFound=true;
                           System.out.println("Job id: " + operationJobId );
                           System.out.println("Status : " + operationStatus.toString());
                           if (operationStatus.asText().equals("SUCCEEDED")){
                           	success=true;
                           }
                           else{
                               System.out.println("Video analysis failed");
                           }
   
                           sqs.deleteMessage(sqsQueueUrl,message.getReceiptHandle());
                       }
   
                       else{
                           System.out.println("Job received was not job " +  startJobId);
                           //Delete unknown message. Consider moving message to dead letter queue
                           sqs.deleteMessage(sqsQueueUrl,message.getReceiptHandle());
                       }
                   }
               }
               else {
                   Thread.sleep(5000);
               }
           } while (!jobFound);
   
           System.out.println("Finished processing video");
           return success;
       }
     
   
       private static void StartLabelDetection(String bucket, String video) throws Exception{
       	
           NotificationChannel channel= new NotificationChannel()
                   .withSNSTopicArn(snsTopicArn)
                   .withRoleArn(roleArn);
   
   
           StartLabelDetectionRequest req = new StartLabelDetectionRequest()
                   .withVideo(new Video()
                           .withS3Object(new S3Object()
                                   .withBucket(bucket)
                                   .withName(video)))
                   .withMinConfidence(50F)
                   .withJobTag("DetectingLabels")
                   .withNotificationChannel(channel);
   
           StartLabelDetectionResult startLabelDetectionResult = rek.startLabelDetection(req);
           startJobId=startLabelDetectionResult.getJobId();
           
       }
     
       private static void GetLabelDetectionResults() throws Exception{
   
           int maxResults=10;
           String paginationToken=null;
           GetLabelDetectionResult labelDetectionResult=null;
   
           do {
               if (labelDetectionResult !=null){
                   paginationToken = labelDetectionResult.getNextToken();
               }
   
               GetLabelDetectionRequest labelDetectionRequest= new GetLabelDetectionRequest()
                       .withJobId(startJobId)
                       .withSortBy(LabelDetectionSortBy.TIMESTAMP)
                       .withMaxResults(maxResults)
                       .withNextToken(paginationToken);
   
   
               labelDetectionResult = rek.getLabelDetection(labelDetectionRequest);
   
               VideoMetadata videoMetaData=labelDetectionResult.getVideoMetadata();
   
               System.out.println("Format: " + videoMetaData.getFormat());
               System.out.println("Codec: " + videoMetaData.getCodec());
               System.out.println("Duration: " + videoMetaData.getDurationMillis());
               System.out.println("FrameRate: " + videoMetaData.getFrameRate());
   
   
               //Show labels, confidence and detection times
               List<LabelDetection> detectedLabels= labelDetectionResult.getLabels();
   
               for (LabelDetection detectedLabel: detectedLabels) {
                   long seconds=detectedLabel.getTimestamp();
                   Label label=detectedLabel.getLabel();
                   System.out.println("Millisecond: " + Long.toString(seconds) + " ");
                   
                   System.out.println("   Label:" + label.getName()); 
                   System.out.println("   Confidence:" + detectedLabel.getLabel().getConfidence().toString());
         
                   List<Instance> instances = label.getInstances();
                   System.out.println("   Instances of " + label.getName());
                   if (instances.isEmpty()) {
                       System.out.println("        " + "None");
                   } else {
                       for (Instance instance : instances) {
                           System.out.println("        Confidence: " + instance.getConfidence().toString());
                           System.out.println("        Bounding box: " + instance.getBoundingBox().toString());
                       }
                   }
                   System.out.println("   Parent labels for " + label.getName() + ":");
                   List<Parent> parents = label.getParents();
                   if (parents.isEmpty()) {
                       System.out.println("        None");
                   } else {
                       for (Parent parent : parents) {
                           System.out.println("        " + parent.getName());
                       }
                   }
                   System.out.println();
               }
           } while (labelDetectionResult !=null && labelDetectionResult.getNextToken() != null);
   
       } 
   
       // Creates an SNS topic and SQS queue. The queue is subscribed to the topic. 
       static void CreateTopicandQueue()
       {
           //create a new SNS topic
           snsTopicName="AmazonRekognitionTopic" + Long.toString(System.currentTimeMillis());
           CreateTopicRequest createTopicRequest = new CreateTopicRequest(snsTopicName);
           CreateTopicResult createTopicResult = sns.createTopic(createTopicRequest);
           snsTopicArn=createTopicResult.getTopicArn();
           
           //Create a new SQS Queue
           sqsQueueName="AmazonRekognitionQueue" + Long.toString(System.currentTimeMillis());
           final CreateQueueRequest createQueueRequest = new CreateQueueRequest(sqsQueueName);
           sqsQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();
           sqsQueueArn = sqs.getQueueAttributes(sqsQueueUrl, Arrays.asList("QueueArn")).getAttributes().get("QueueArn");
           
           //Subscribe SQS queue to SNS topic
           String sqsSubscriptionArn = sns.subscribe(snsTopicArn, "sqs", sqsQueueArn).getSubscriptionArn();
           
           // Authorize queue
             Policy policy = new Policy().withStatements(
                     new Statement(Effect.Allow)
                     .withPrincipals(Principal.AllUsers)
                     .withActions(SQSActions.SendMessage)
                     .withResources(new Resource(sqsQueueArn))
                     .withConditions(new Condition().withType("ArnEquals").withConditionKey("aws:SourceArn").withValues(snsTopicArn))
                     );
                     
   
             Map queueAttributes = new HashMap();
             queueAttributes.put(QueueAttributeName.Policy.toString(), policy.toJson());
             sqs.setQueueAttributes(new SetQueueAttributesRequest(sqsQueueUrl, queueAttributes)); 
           
   
            System.out.println("Topic arn: " + snsTopicArn);
            System.out.println("Queue arn: " + sqsQueueArn);
            System.out.println("Queue url: " + sqsQueueUrl);
            System.out.println("Queue sub arn: " + sqsSubscriptionArn );
        }
       static void DeleteTopicandQueue()
       {
           if (sqs !=null) {
               sqs.deleteQueue(sqsQueueUrl);
               System.out.println("SQS queue deleted");
           }
           
           if (sns!=null) {
               sns.deleteTopic(snsTopicArn);
               System.out.println("SNS topic deleted");
           }
       }
   }
   ```

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

   `main` 関数内:
   + `roleArn` を、[Amazon Rekognition Video を設定するには](api-video-roles.md#configure-rekvid-procedure) のステップ 7 で作成した IAM サービスロールの ARN に置き換えます。
   + `amzn-s3-demo-bucket` と `video` の値を、ステップ 2 で指定したバケット名とビデオファイル名に置き換えます。
   + Rekognition セッションを作成する行の `profile_name` の値を、自分のデベロッパープロファイル名に置き換えます。
   + 設定パラメータにフィルター条件を含めることもできます。例えば、目的の値のリストと共に `LabelsInclusionFilter` または `LabelsExclusionFilter` を使用できます。以下のコードでは、`Features` と `Settings` セクションのコメントを外して独自の値を指定することで、返される結果を興味のあるラベルだけに制限できます。
   + `GetLabelDetection` の呼び出しでは、`SortBy` および `AggregateBy` 引数の値を指定できます。時間で並べ替える場合は、`SortBy` 入力パラメータの値を `TIMESTAMP` に設定します。エンティティで並べ替えるには、実行するオペレーションにとって適切な値を `SortBy` 入力パラメータで使用します。結果をタイムスタンプ別に集計するには、`AggregateBy` パラメータの値を `TIMESTAMPS` に設定します。ビデオセグメント別に集計するには、`SEGMENTS` を使用します。

   コードの例では、`policy = """""".format(sqsQueueArn, self.snsTopicArn)` 行の引用符内に次の IAM ポリシーを配置します。

   ```
   ## Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   import boto3
   import json
   import sys
   import time
   
   class VideoDetect:
   
       jobId = ''
   
       roleArn = ''
       bucket = ''
       video = ''
       startJobId = ''
   
       sqsQueueUrl = ''
       snsTopicArn = ''
       processType = ''
   
       def __init__(self, role, bucket, video, client, rek, sqs, sns):
           self.roleArn = role
           self.bucket = bucket
           self.video = video
           self.client = client
           self.rek = rek
           self.sqs = sqs
           self.sns = sns
   
       def GetSQSMessageSuccess(self):
   
           jobFound = False
           succeeded = False
   
           dotLine = 0
           while jobFound == False:
               sqsResponse = self.sqs.receive_message(QueueUrl=self.sqsQueueUrl, MessageAttributeNames=['ALL'],
                                                      MaxNumberOfMessages=10)
   
               if sqsResponse:
   
                   if 'Messages' not in sqsResponse:
                       if dotLine < 40:
                           print('.', end='')
                           dotLine = dotLine + 1
                       else:
                           print()
                           dotLine = 0
                       sys.stdout.flush()
                       time.sleep(5)
                       continue
   
                   for message in sqsResponse['Messages']:
                       notification = json.loads(message['Body'])
                       rekMessage = json.loads(notification['Message'])
                       print(rekMessage['JobId'])
                       print(rekMessage['Status'])
                       if rekMessage['JobId'] == self.startJobId:
                           print('Matching Job Found:' + rekMessage['JobId'])
                           jobFound = True
                           if (rekMessage['Status'] == 'SUCCEEDED'):
                               succeeded = True
   
                           self.sqs.delete_message(QueueUrl=self.sqsQueueUrl,
                                                   ReceiptHandle=message['ReceiptHandle'])
                       else:
                           print("Job didn't match:" +
                                 str(rekMessage['JobId']) + ' : ' + self.startJobId)
                       # Delete the unknown message. Consider sending to dead letter queue
                       self.sqs.delete_message(QueueUrl=self.sqsQueueUrl,
                                               ReceiptHandle=message['ReceiptHandle'])
   
           return succeeded
   
       def StartLabelDetection(self):
           response = self.rek.start_label_detection(Video={'S3Object': {'Bucket': self.bucket, 'Name': self.video}},
                                                     NotificationChannel={'RoleArn': self.roleArn,
                                                                          'SNSTopicArn': self.snsTopicArn},
                                                     MinConfidence=90,
                                                     # Filtration options, uncomment and add desired labels to filter returned labels
                                                     # Features=['GENERAL_LABELS'],
                                                     # Settings={
                                                     # 'GeneralLabels': {
                                                     # 'LabelInclusionFilters': ['Clothing']
                                                     # }}
                                                      )
   
           self.startJobId = response['JobId']
           print('Start Job Id: ' + self.startJobId)
   
       def GetLabelDetectionResults(self):
           maxResults = 10
           paginationToken = ''
           finished = False
   
           while finished == False:
               response = self.rek.get_label_detection(JobId=self.startJobId,
                                                       MaxResults=maxResults,
                                                       NextToken=paginationToken,
                                                       SortBy='TIMESTAMP',
                                                       AggregateBy="TIMESTAMPS")
   
               print('Codec: ' + response['VideoMetadata']['Codec'])
               print('Duration: ' + str(response['VideoMetadata']['DurationMillis']))
               print('Format: ' + response['VideoMetadata']['Format'])
               print('Frame rate: ' + str(response['VideoMetadata']['FrameRate']))
               print()
   
               for labelDetection in response['Labels']:
                   label = labelDetection['Label']
   
                   print("Timestamp: " + str(labelDetection['Timestamp']))
                   print("   Label: " + label['Name'])
                   print("   Confidence: " + str(label['Confidence']))
                   print("   Instances:")
                   for instance in label['Instances']:
                       print("      Confidence: " + str(instance['Confidence']))
                       print("      Bounding box")
                       print("        Top: " + str(instance['BoundingBox']['Top']))
                       print("        Left: " + str(instance['BoundingBox']['Left']))
                       print("        Width: " + str(instance['BoundingBox']['Width']))
                       print("        Height: " + str(instance['BoundingBox']['Height']))
                       print()
                   print()
   
                   print("Parents:")
                   for parent in label['Parents']:
                       print("   " + parent['Name'])
   
                   print("Aliases:")
                   for alias in label['Aliases']:
                       print("   " + alias['Name'])
   
                   print("Categories:")
                   for category in label['Categories']:
                       print("   " + category['Name'])
                   print("----------")
                   print()
   
                   if 'NextToken' in response:
                       paginationToken = response['NextToken']
                   else:
                       finished = True
   
       def CreateTopicandQueue(self):
   
           millis = str(int(round(time.time() * 1000)))
   
           # Create SNS topic
   
           snsTopicName = "AmazonRekognitionExample" + millis
   
           topicResponse = self.sns.create_topic(Name=snsTopicName)
           self.snsTopicArn = topicResponse['TopicArn']
   
           # create SQS queue
           sqsQueueName = "AmazonRekognitionQueue" + millis
           self.sqs.create_queue(QueueName=sqsQueueName)
           self.sqsQueueUrl = self.sqs.get_queue_url(QueueName=sqsQueueName)['QueueUrl']
   
           attribs = self.sqs.get_queue_attributes(QueueUrl=self.sqsQueueUrl,
                                                   AttributeNames=['QueueArn'])['Attributes']
   
           sqsQueueArn = attribs['QueueArn']
   
           # Subscribe SQS queue to SNS topic
           self.sns.subscribe(
               TopicArn=self.snsTopicArn,
               Protocol='sqs',
               Endpoint=sqsQueueArn)
   
           # Authorize SNS to write SQS queue 
           # Insert the policy from the documentation from 
           policy = """
           {{
              "Version":"2012-10-17",              
              "Statement":[
               {{
                   "Sid":"MyPolicy",
                   "Effect":"Allow",
                   "Principal" : {{"AWS" : "*"}},
                   "Action":"SQS:SendMessage",
                   "Resource": "{}",
                   "Condition":{{
                       "ArnEquals":{{
                           "aws:SourceArn": "{}"
                        }}
                   }}
               }}
               ]
           }}""".format(sqsQueueArn, self.snsTopicArn)
   
           response = self.sqs.set_queue_attributes(
               QueueUrl=self.sqsQueueUrl,
               Attributes={
                   'Policy': policy
               })
   
       def DeleteTopicandQueue(self):
           self.sqs.delete_queue(QueueUrl=self.sqsQueueUrl)
           self.sns.delete_topic(TopicArn=self.snsTopicArn)
   
   def main():
       
       roleArn = 'role-arn'
       bucket = 'bucket-name'
       video = 'video-name'
   
       session = boto3.Session(profile_name='profile-name')
       client = session.client('rekognition')
       rek = boto3.client('rekognition')
       sqs = boto3.client('sqs')
       sns = boto3.client('sns')
   
       analyzer = VideoDetect(roleArn, bucket, video, client, rek, sqs, sns)
       analyzer.CreateTopicandQueue()
   
       analyzer.StartLabelDetection()
       if analyzer.GetSQSMessageSuccess() == True:
           analyzer.GetLabelDetectionResults()
   
       analyzer.DeleteTopicandQueue()
   
   if __name__ == "__main__":
       main()
   ```

------
#### [ Node.Js ]

    次のサンプルコードでは
   + `REGION` の値を、アカウントのオペレーティングリージョンの名前に置き換えます。
   + `amzn-s3-demo-bucket` の値を、ビデオファイルが保存されているAmazon S3 バケットの名前に置き換えます。
   + `videoName` の値を、Amazon S3 バケット内のビデオファイル名に置き換えます。
   +  Rekognition セッションを作成する行の `profile_name` の値を、自分のデベロッパープロファイル名に置き換えます。
   + `roleArn` を、[Amazon Rekognition Video を設定するには](api-video-roles.md#configure-rekvid-procedure) のステップ 7 で作成した IAM サービスロールの ARN に置き換えます。

   ```
   import { CreateQueueCommand, GetQueueAttributesCommand, GetQueueUrlCommand, 
     SetQueueAttributesCommand, DeleteQueueCommand, ReceiveMessageCommand, DeleteMessageCommand } from  "@aws-sdk/client-sqs";
   import {CreateTopicCommand, SubscribeCommand, DeleteTopicCommand } from "@aws-sdk/client-sns";
   import  { SQSClient } from "@aws-sdk/client-sqs";
   import  { SNSClient } from "@aws-sdk/client-sns";
   import  { RekognitionClient, StartLabelDetectionCommand, GetLabelDetectionCommand } from "@aws-sdk/client-rekognition";
   import { stdout } from "process";
   import {fromIni} from '@aws-sdk/credential-providers';
   
   // Set the AWS Region.
   const REGION = "region-name"; //e.g. "us-east-1"
   const profileName = "profile-name"
   // Create SNS service object.
   const sqsClient = new SQSClient({ region: REGION, 
     credentials: fromIni({profile: profileName,}), });
   const snsClient = new SNSClient({ region: REGION, 
     credentials: fromIni({profile: profileName,}), });
   const rekClient = new RekognitionClient({region: REGION, 
     credentials: fromIni({profile: profileName,}), 
   });
   
   // Set bucket and video variables
   const bucket = "bucket-name";
   const videoName = "video-name";
   const roleArn = "role-arn"
   var startJobId = ""
   
   var ts = Date.now();
   const snsTopicName = "AmazonRekognitionExample" + ts;
   const snsTopicParams = {Name: snsTopicName}
   const sqsQueueName = "AmazonRekognitionQueue-" + ts;
   
   // Set the parameters
   const sqsParams = {
     QueueName: sqsQueueName, //SQS_QUEUE_URL
     Attributes: {
       DelaySeconds: "60", // Number of seconds delay.
       MessageRetentionPeriod: "86400", // Number of seconds delay.
     },
   };
   
   const createTopicandQueue = async () => {
     try {
       // Create SNS topic
       const topicResponse = await snsClient.send(new CreateTopicCommand(snsTopicParams));
       const topicArn = topicResponse.TopicArn
       console.log("Success", topicResponse);
       // Create SQS Queue
       const sqsResponse = await sqsClient.send(new CreateQueueCommand(sqsParams));
       console.log("Success", sqsResponse);
       const sqsQueueCommand = await sqsClient.send(new GetQueueUrlCommand({QueueName: sqsQueueName}))
       const sqsQueueUrl = sqsQueueCommand.QueueUrl
       const attribsResponse = await sqsClient.send(new GetQueueAttributesCommand({QueueUrl: sqsQueueUrl, AttributeNames: ['QueueArn']}))
       const attribs = attribsResponse.Attributes
       console.log(attribs)
       const queueArn = attribs.QueueArn
       // subscribe SQS queue to SNS topic
       const subscribed = await snsClient.send(new SubscribeCommand({TopicArn: topicArn, Protocol:'sqs', Endpoint: queueArn}))
       const policy = {
         Version: "2012-10-17",&TCX5-2025-waiver;                
         Statement: [
           {
             Sid: "MyPolicy",
             Effect: "Allow",
             Principal: {AWS: "*"},
             Action: "SQS:SendMessage",
             Resource: queueArn,
             Condition: {
               ArnEquals: {
                 'aws:SourceArn': topicArn
               }
             }
           }
         ]
       };
   
       const response = sqsClient.send(new SetQueueAttributesCommand({QueueUrl: sqsQueueUrl, Attributes: {Policy: JSON.stringify(policy)}}))
       console.log(response)
       console.log(sqsQueueUrl, topicArn)
       return [sqsQueueUrl, topicArn]
   
     } catch (err) {
       console.log("Error", err);
     }
   };
   
   const startLabelDetection = async (roleArn, snsTopicArn) => {
     try {
       //Initiate label detection and update value of startJobId with returned Job ID
      const labelDetectionResponse = await rekClient.send(new StartLabelDetectionCommand({Video:{S3Object:{Bucket:bucket, Name:videoName}}, 
         NotificationChannel:{RoleArn: roleArn, SNSTopicArn: snsTopicArn}}));
         startJobId = labelDetectionResponse.JobId
         console.log(`JobID: ${startJobId}`)
         return startJobId
     } catch (err) {
       console.log("Error", err);
     }
   };
   
   const getLabelDetectionResults = async(startJobId) => {
     console.log("Retrieving Label Detection results")
     // Set max results, paginationToken and finished will be updated depending on response values
     var maxResults = 10
     var paginationToken = ''
     var finished = false
   
     // Begin retrieving label detection results
     while (finished == false){
       var response = await rekClient.send(new GetLabelDetectionCommand({JobId: startJobId, MaxResults: maxResults, 
         NextToken: paginationToken, SortBy:'TIMESTAMP'}))
         // Log metadata
         console.log(`Codec: ${response.VideoMetadata.Codec}`)
         console.log(`Duration: ${response.VideoMetadata.DurationMillis}`)
         console.log(`Format: ${response.VideoMetadata.Format}`)
         console.log(`Frame Rate: ${response.VideoMetadata.FrameRate}`)
         console.log()
         // For every detected label, log label, confidence, bounding box, and timestamp
         response.Labels.forEach(labelDetection => {
           var label = labelDetection.Label
           console.log(`Timestamp: ${labelDetection.Timestamp}`)
           console.log(`Label: ${label.Name}`)
           console.log(`Confidence: ${label.Confidence}`)
           console.log("Instances:")
           label.Instances.forEach(instance =>{
             console.log(`Confidence: ${instance.Confidence}`)
             console.log("Bounding Box:")
             console.log(`Top: ${instance.Confidence}`)
             console.log(`Left: ${instance.Confidence}`)
             console.log(`Width: ${instance.Confidence}`)
             console.log(`Height: ${instance.Confidence}`)
             console.log()
           })
         console.log()
         // Log parent if found
         console.log("   Parents:")
         label.Parents.forEach(parent =>{
           console.log(`    ${parent.Name}`)
         })
         console.log()
         // Searh for pagination token, if found, set variable to next token
         if (String(response).includes("NextToken")){
           paginationToken = response.NextToken
   
         }else{
           finished = true
         }
   
         })
     }
   }
   
   // Checks for status of job completion
   const getSQSMessageSuccess = async(sqsQueueUrl, startJobId) => {
     try {
       // Set job found and success status to false initially
       var jobFound = false
       var succeeded = false
       var dotLine = 0
       // while not found, continue to poll for response
       while (jobFound == false){
         var sqsReceivedResponse = await sqsClient.send(new ReceiveMessageCommand({QueueUrl:sqsQueueUrl, 
           MaxNumberOfMessages:'ALL', MaxNumberOfMessages:10}));
         if (sqsReceivedResponse){
           var responseString = JSON.stringify(sqsReceivedResponse)
           if (!responseString.includes('Body')){
             if (dotLine < 40) {
               console.log('.')
               dotLine = dotLine + 1
             }else {
               console.log('')
               dotLine = 0 
             };
             stdout.write('', () => {
               console.log('');
             });
             await new Promise(resolve => setTimeout(resolve, 5000));
             continue
           }
         }
   
         // Once job found, log Job ID and return true if status is succeeded
         for (var message of sqsReceivedResponse.Messages){
           console.log("Retrieved messages:")
           var notification = JSON.parse(message.Body)
           var rekMessage = JSON.parse(notification.Message)
           var messageJobId = rekMessage.JobId
           if (String(rekMessage.JobId).includes(String(startJobId))){
             console.log('Matching job found:')
             console.log(rekMessage.JobId)
             jobFound = true
             console.log(rekMessage.Status)
             if (String(rekMessage.Status).includes(String("SUCCEEDED"))){
               succeeded = true
               console.log("Job processing succeeded.")
               var sqsDeleteMessage = await sqsClient.send(new DeleteMessageCommand({QueueUrl:sqsQueueUrl, ReceiptHandle:message.ReceiptHandle}));
             }
           }else{
             console.log("Provided Job ID did not match returned ID.")
             var sqsDeleteMessage = await sqsClient.send(new DeleteMessageCommand({QueueUrl:sqsQueueUrl, ReceiptHandle:message.ReceiptHandle}));
           }
         }
       }
     return succeeded
     } catch(err) {
       console.log("Error", err);
     }
   };
   
   // Start label detection job, sent status notification, check for success status
   // Retrieve results if status is "SUCEEDED", delete notification queue and topic
   const runLabelDetectionAndGetResults = async () => {
     try {
       const sqsAndTopic = await createTopicandQueue();
       const startLabelDetectionRes = await startLabelDetection(roleArn, sqsAndTopic[1]);
       const getSQSMessageStatus = await getSQSMessageSuccess(sqsAndTopic[0], startLabelDetectionRes)
       console.log(getSQSMessageSuccess)
       if (getSQSMessageSuccess){
         console.log("Retrieving results:")
         const results = await getLabelDetectionResults(startLabelDetectionRes)
       }
       const deleteQueue = await sqsClient.send(new DeleteQueueCommand({QueueUrl: sqsAndTopic[0]}));
       const deleteTopic = await snsClient.send(new DeleteTopicCommand({TopicArn: sqsAndTopic[1]}));
       console.log("Successfully deleted.")
     } catch (err) {
       console.log("Error", err);
     }
   };
   
   runLabelDetectionAndGetResults()
   ```

------
#### [ 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/VideoDetect.java)] です。

   ```
   import com.fasterxml.jackson.core.JsonProcessingException;
   import com.fasterxml.jackson.databind.JsonMappingException;
   import com.fasterxml.jackson.databind.JsonNode;
   import com.fasterxml.jackson.databind.ObjectMapper;
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.StartLabelDetectionResponse;
   import software.amazon.awssdk.services.rekognition.model.NotificationChannel;
   import software.amazon.awssdk.services.rekognition.model.S3Object;
   import software.amazon.awssdk.services.rekognition.model.Video;
   import software.amazon.awssdk.services.rekognition.model.StartLabelDetectionRequest;
   import software.amazon.awssdk.services.rekognition.model.GetLabelDetectionRequest;
   import software.amazon.awssdk.services.rekognition.model.GetLabelDetectionResponse;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   import software.amazon.awssdk.services.rekognition.model.LabelDetectionSortBy;
   import software.amazon.awssdk.services.rekognition.model.VideoMetadata;
   import software.amazon.awssdk.services.rekognition.model.LabelDetection;
   import software.amazon.awssdk.services.rekognition.model.Label;
   import software.amazon.awssdk.services.rekognition.model.Instance;
   import software.amazon.awssdk.services.rekognition.model.Parent;
   import software.amazon.awssdk.services.sqs.SqsClient;
   import software.amazon.awssdk.services.sqs.model.Message;
   import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
   import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
   import java.util.List;
   //snippet-end:[rekognition.java2.recognize_video_detect.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 VideoDetect {
   
    private static String startJobId ="";
    public static void main(String[] args) {
   
        final String usage = "\n" +
            "Usage: " +
            "   <bucket> <video> <queueUrl> <topicArn> <roleArn>\n\n" +
            "Where:\n" +
            "   bucket - The name of the bucket in which the video is located (for example, (for example, amzn-s3-demo-bucket). \n\n"+
            "   video - The name of the video (for example, people.mp4). \n\n" +
            "   queueUrl- The URL of a SQS queue. \n\n" +
            "   topicArn - The ARN of the Amazon Simple Notification Service (Amazon SNS) topic. \n\n" +
            "   roleArn - The ARN of the AWS Identity and Access Management (IAM) role to use. \n\n" ;
   
        if (args.length != 5) {
            System.out.println(usage);
            System.exit(1);
        }
   
        String bucket = args[0];
        String video = args[1];
        String queueUrl = args[2];
        String topicArn = args[3];
        String roleArn = args[4];
        Region region = Region.US_WEST_2;
        RekognitionClient rekClient = RekognitionClient.builder()
            .region(region)
            .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
            .build();
   
        SqsClient sqs = SqsClient.builder()
            .region(Region.US_WEST_2)
            .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
            .build();
   
        NotificationChannel channel = NotificationChannel.builder()
            .snsTopicArn(topicArn)
            .roleArn(roleArn)
            .build();
   
        startLabels(rekClient, channel, bucket, video);
        getLabelJob(rekClient, sqs,  queueUrl);
        System.out.println("This example is done!");
        sqs.close();
        rekClient.close();
    }
   
    // snippet-start:[rekognition.java2.recognize_video_detect.main]
    public static void startLabels(RekognitionClient rekClient,
                                   NotificationChannel channel,
                                   String bucket,
                                   String video) {
        try {
            S3Object s3Obj = S3Object.builder()
                .bucket(bucket)
                .name(video)
                .build();
   
            Video vidOb = Video.builder()
                .s3Object(s3Obj)
                .build();
   
            StartLabelDetectionRequest labelDetectionRequest = StartLabelDetectionRequest.builder()
                .jobTag("DetectingLabels")
                .notificationChannel(channel)
                .video(vidOb)
                .minConfidence(50F)
                .build();
   
            StartLabelDetectionResponse labelDetectionResponse = rekClient.startLabelDetection(labelDetectionRequest);
            startJobId = labelDetectionResponse.jobId();
   
            boolean ans = true;
            String status = "";
            int yy = 0;
            while (ans) {
   
                GetLabelDetectionRequest detectionRequest = GetLabelDetectionRequest.builder()
                    .jobId(startJobId)
                    .maxResults(10)
                    .build();
   
                GetLabelDetectionResponse result = rekClient.getLabelDetection(detectionRequest);
                status = result.jobStatusAsString();
   
                if (status.compareTo("SUCCEEDED") == 0)
                    ans = false;
                else
                    System.out.println(yy +" status is: "+status);
   
                Thread.sleep(1000);
                yy++;
            }
   
            System.out.println(startJobId +" status is: "+status);
   
        } catch(RekognitionException | InterruptedException e) {
            e.getMessage();
            System.exit(1);
        }
    }
   
    public static void getLabelJob(RekognitionClient rekClient, SqsClient sqs, String queueUrl) {
   
        List<Message> messages;
        ReceiveMessageRequest messageRequest = ReceiveMessageRequest.builder()
            .queueUrl(queueUrl)
            .build();
   
        try {
            messages = sqs.receiveMessage(messageRequest).messages();
   
            if (!messages.isEmpty()) {
                for (Message message: messages) {
                    String notification = message.body();
   
                    // Get the status and job id from the notification
                    ObjectMapper mapper = new ObjectMapper();
                    JsonNode jsonMessageTree = mapper.readTree(notification);
                    JsonNode messageBodyText = jsonMessageTree.get("Message");
                    ObjectMapper operationResultMapper = new ObjectMapper();
                    JsonNode jsonResultTree = operationResultMapper.readTree(messageBodyText.textValue());
                    JsonNode operationJobId = jsonResultTree.get("JobId");
                    JsonNode operationStatus = jsonResultTree.get("Status");
                    System.out.println("Job found in JSON is " + operationJobId);
   
                    DeleteMessageRequest deleteMessageRequest = DeleteMessageRequest.builder()
                        .queueUrl(queueUrl)
                        .build();
   
                    String jobId = operationJobId.textValue();
                    if (startJobId.compareTo(jobId)==0) {
                        System.out.println("Job id: " + operationJobId );
                        System.out.println("Status : " + operationStatus.toString());
   
                        if (operationStatus.asText().equals("SUCCEEDED"))
                            GetResultsLabels(rekClient);
                        else
                            System.out.println("Video analysis failed");
   
                        sqs.deleteMessage(deleteMessageRequest);
                    }
   
                    else{
                        System.out.println("Job received was not job " +  startJobId);
                        sqs.deleteMessage(deleteMessageRequest);
                    }
                }
            }
   
        } catch(RekognitionException e) {
            e.getMessage();
            System.exit(1);
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
   
    // Gets the job results by calling GetLabelDetection
    private static void GetResultsLabels(RekognitionClient rekClient) {
   
        int maxResults=10;
        String paginationToken=null;
        GetLabelDetectionResponse labelDetectionResult=null;
   
        try {
            do {
                if (labelDetectionResult !=null)
                    paginationToken = labelDetectionResult.nextToken();
   
   
                GetLabelDetectionRequest labelDetectionRequest= GetLabelDetectionRequest.builder()
                    .jobId(startJobId)
                    .sortBy(LabelDetectionSortBy.TIMESTAMP)
                    .maxResults(maxResults)
                    .nextToken(paginationToken)
                    .build();
   
                labelDetectionResult = rekClient.getLabelDetection(labelDetectionRequest);
                VideoMetadata videoMetaData=labelDetectionResult.videoMetadata();
                System.out.println("Format: " + videoMetaData.format());
                System.out.println("Codec: " + videoMetaData.codec());
                System.out.println("Duration: " + videoMetaData.durationMillis());
                System.out.println("FrameRate: " + videoMetaData.frameRate());
   
                List<LabelDetection> detectedLabels= labelDetectionResult.labels();
                for (LabelDetection detectedLabel: detectedLabels) {
                    long seconds=detectedLabel.timestamp();
                    Label label=detectedLabel.label();
                    System.out.println("Millisecond: " + seconds + " ");
   
                    System.out.println("   Label:" + label.name());
                    System.out.println("   Confidence:" + detectedLabel.label().confidence().toString());
   
                    List<Instance> instances = label.instances();
                    System.out.println("   Instances of " + label.name());
   
                    if (instances.isEmpty()) {
                        System.out.println("        " + "None");
                    } else {
                        for (Instance instance : instances) {
                            System.out.println("        Confidence: " + instance.confidence().toString());
                            System.out.println("        Bounding box: " + instance.boundingBox().toString());
                        }
                    }
                    System.out.println("   Parent labels for " + label.name() + ":");
                    List<Parent> parents = label.parents();
   
                    if (parents.isEmpty()) {
                        System.out.println("        None");
                    } else {
                        for (Parent parent : parents) {
                            System.out.println("   " + parent.name());
                        }
                    }
                    System.out.println();
                }
            } while (labelDetectionResult !=null && labelDetectionResult.nextToken() != null);
   
        } catch(RekognitionException e) {
            e.getMessage();
            System.exit(1);
        }
    }
    // snippet-end:[rekognition.java2.recognize_video_detect.main]
   }
   ```

------

1. コードをビルドして実行します。オペレーションの完了までに時間がかかる場合があります。完了すると、ビデオ内で検出されたラベルのリストが表示されます。詳細については、「[ビデオ内のラベルの検出](labels-detecting-labels-video.md)」を参照してください。

# を使用したビデオの分析 AWS Command Line Interface
<a name="video-cli-commands"></a>

 AWS Command Line Interface (AWS CLI) を使用して Amazon Rekognition Video オペレーションを呼び出すことができます。設計パターンは、 AWS SDK for Java または他の AWS SDK で Amazon Rekognition Video API を使用するのと同じです。 SDKs 詳細については、「[Amazon Rekognition Video API の概要](video.md#video-api-overview)」を参照してください。次の手順は、 を使用してビデオ内のラベル AWS CLI を検出する方法を示しています。

ビデオ内のラベルの検出を開始するには、`start-label-detection` を呼び出します。Amazon Rekognition によるビデオの分析が完了すると、`--notification-channel` の `start-label-detection` パラメータで指定されている Amazon SNS トピックに完了ステータスが送信されます。Amazon Simple Queue Service (Amazon SQS) キューを Amazon SNS トピックにサブスクライブすることで、完了ステータスを取得できます。次に [[receive-message](https://docs.aws.amazon.com/cli/latest/reference/sqs/receive-message.html)] をポーリングして Amazon SQS キューから完了ステータスを取得します。

`StartLabelDetection` を呼び出すときは、`LabelsInclusionFilter` および/または `LabelsExclusionFilter` 引数にフィルター引数を指定して結果をフィルタリングできます。詳細については、「[ビデオ内のラベルの検出](labels-detecting-labels-video.md)」を参照してください。

完了ステータスの通知は、`receive-message` 応答内の JSON 構造です。この JSON を応答から抽出する必要があります。完了ステータス JSON については、「[リファレンス: ビデオ分析結果の通知](video-notification-payload.md)」を参照してください。JSON 完了ステータスの `Status` フィールドの値が `SUCCEEDED` の場合、`get-label-detection` を呼び出すことでビデオ分析リクエストの結果を取得できます。`GetLabelDetection` を呼び出すときは、`SortBy` および `AggregateBy` 引数を使用して返された結果をソートして集計できます。

以下の手順には、Amazon SQS キューをポーリングするコードは含まれていません。また、Amazon SQS キューから返される JSON を解析するコードも含まれていません。Java での例については、「[Java または Python を使用した、Amazon S3 バケットに保存されたビデオの分析 (SDK)](video-analyzing-with-sqs.md)」を参照してください。

## 前提条件
<a name="video-prerequisites"></a>

この手順を実行するには、 AWS CLI がインストールされている必要があります。詳細については、「[Amazon Rekognition の開始方法](getting-started.md)」を参照してください。使用する AWS アカウントには、Amazon Rekognition API に対するアクセス許可が必要です。詳細については、[[Amazon Rekognition によって定義されるアクション](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonrekognition.html#amazonrekognition-actions-as-permissions)] を参照してください。

**Amazon Rekognition Video を設定してビデオをアップロードするには**

1. Amazon Rekognition Video へのユーザーアクセスを設定し、Amazon SNS への Amazon Rekognition Video アクセスを設定します。詳細については、「[Amazon Rekognition Video の設定](api-video-roles.md)」を参照してください。

1. S3 バケットに MOV あるいは MPEG-4 形式のビデオファイルをアップロードします。開発やテストには、長さが 30 秒以内の短いビデオを使うことをお勧めします。

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

**ビデオ内のラベルを検出するには**

1. 次の AWS CLI コマンドを実行して、ビデオ内のラベルの検出を開始します。

   ```
   aws rekognition start-label-detection --video '{"S3Object":{"Bucket":"amzn-s3-demo-bucket","Name":"video-name"}}' \
    --notification-channel '{"SNSTopicArn":"TopicARN","RoleArn":"RoleARN"}' \
   --region region-name  \ 
   --features GENERAL_LABELS \
   --profile profile-name \
   --settings "{"GeneralLabels":{"LabelInclusionFilters":["Car"]}}
   ```

   以下の値を更新します。
   + `amzn-s3-demo-bucket` と `videofile` を、ステップ 2 で指定した Amazon S3 バケット名とファイル名に変更します。
   + `us-east-1` を、使用している AWS リージョンに変更します。
   + Rekognition セッションを作成する行の `profile_name` の値を、自分のデベロッパープロファイル名に置き換えます。
   + `TopicARN` を、[Amazon Rekognition Video の設定](api-video-roles.md) のステップ 3 で作成した Amazon SNS トピックの ARN に変更します。
   + `RoleARN` を、[Amazon Rekognition Video の設定](api-video-roles.md) のステップ 7 で作成した IAM サービスロールの ARN に変更します。
   + 必要に応じて、`endpoint-url` を指定できます。AWS CLI は、指定されたリージョンに基づいて適切なエンドポイント URL を自動的に決定します。ただし、[[プライベート VPC の](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html#what-is-privatelink)] エンドポイントを使用している場合は、`endpoint-url` の指定が必要となる場合があります。[[AWS サービスエンドポイント](https://docs.aws.amazon.com/general/latest/gr/rande.html#regional-endpoints)] リソースに、エンドポイント URL を指定するための構文、および各リージョンの名前とコードが記載されています。
   + 設定パラメータにフィルター条件を含めることもできます。例えば、目的の値のリストと共に `LabelsInclusionFilter` または `LabelsExclusionFilter` を使用できます。

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

   ```
   aws rekognition start-label-detection --video "{\"S3Object\":{\"Bucket\":\"amzn-s3-demo-bucket",\"Name\":\"video-name\"}}" --notification-channel "{\"SNSTopicArn\":\"TopicARN\",\"RoleArn\":\"RoleARN\"}" \
   --region us-east-1 --features GENERAL_LABELS --settings "{\"GeneralLabels\":{\"LabelInclusionFilters\":[\"Car\"]}}" --profile profile-name
   ```

1. 応答内の `JobId` の値に注意してください。この応答は次の JSON の例のようになります。

   ```
   {
       "JobId": "547089ce5b9a8a0e7831afa655f42e5d7b5c838553f1a584bf350ennnnnnnnnn"
   }
   ```

1. Amazon SQS キューをポーリングして完了ステータス JSON を取得するコードを書き込みます ([[receive-message](https://docs.aws.amazon.com/cli/latest/reference/sqs/receive-message.html)] を使用)。

1. 完了ステータス JSON から `Status` フィールドを抽出するコードを記述します。

1. の値が `Status`の場合`SUCCEEDED`、次の AWS CLI コマンドを実行してラベル検出結果を表示します。

   ```
   aws rekognition get-label-detection  --job-id JobId \
   --region us-east-1 --sort-by TIMESTAMP aggregate-by TIMESTAMPS
   ```

   以下の値を更新します。
   + `JobId` を、手順 2 でメモしたジョブ識別子に合わせて変更します。
   + `Endpoint` と `us-east-1` を、使用している AWS エンドポイントとリージョンに変更します。

   この結果は、次の JSON の例のようになります。

   ```
   {
       "Labels": [
           {
               "Timestamp": 0,
               "Label": {
                   "Confidence": 99.03720092773438,
                   "Name": "Speech"
               }
           },
           {
               "Timestamp": 0,
               "Label": {
                   "Confidence": 71.6698989868164,
                   "Name": "Pumpkin"
               }
           },
           {
               "Timestamp": 0,
               "Label": {
                   "Confidence": 71.6698989868164,
                   "Name": "Squash"
               }
           },
           {
               "Timestamp": 0,
               "Label": {
                   "Confidence": 71.6698989868164,
                   "Name": "Vegetable"
               }
           }, .......
   ```

# リファレンス: ビデオ分析結果の通知
<a name="video-notification-payload"></a>

Amazon Rekognition は、完了ステータスを含む Amazon Rekognition Video の分析リクエストの結果を、Amazon Simple Notification Service (Amazon SNS) トピックに発行します。Amazon SNS トピックから通知を取得するには、Amazon Simple Queue Service キューまたは AWS Lambda 関数を使用します。詳細については、「[Amazon Rekognition Video オペレーションを呼び出す](api-video.md)」を参照してください。例については、[Java または Python を使用した、Amazon S3 バケットに保存されたビデオの分析 (SDK)](video-analyzing-with-sqs.md)を参照してください。

ペイロードは次の JSON 形式になります。

```
{
  "JobId": "String",
  "Status": "String",
  "API": "String",
  "JobTag": "String",
  "Timestamp": Number,
  "Video": {
    "S3ObjectName": "String",
    "S3Bucket": "String"
  }
}
```


| 名前 | 説明 | 
| --- | --- | 
|  JobId  |  ジョブ識別子。[StartPersonTracking](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartPersonTracking.html) などの `Start` オペレーションから返されるジョブ識別子と一致します。  | 
|  ステータス  |  ジョブのステータス。有効な値は、SUCCEEDED、FAILED、または ERROR です。  | 
|  API  |  入力ビデオの分析に使用される Amazon Rekognition Video のオペレーション  | 
|  JobTag  |  ジョブ識別子。[StartLabelDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartLabelDetection.html) などの開始オペレーションへの呼び出しで `JobTag` を指定します。  | 
|  タイムスタンプ  |  ジョブ完了時の UNIX タイムスタンプ。  | 
|  動画  |  処理されたビデオに関する詳細。ファイル名やファイルが保存されている Amazon S3 バケットなどが含まれます。  | 

以下の例は、Amazon SNS トピックに送信された正常な処理の通知です。

```
{
  "JobId": "6de014b0-2121-4bf0-9e31-856a18719e22",
  "Status": "SUCCEEDED",
  "API": "LABEL_DETECTION",
  "Message": "",
  "Timestamp": 1502230160926,
  "Video": {
    "S3ObjectName": "video.mpg",
    "S3Bucket": "amzn-s3-demo-bucket"
  }
}
```

# Amazon Rekognition Video のトラブルシューティング
<a name="video-troubleshooting"></a>

Amazon Rekognition Video および保存したビデオの使用に関するトラブルシューティング情報は以下のとおりです。

## Amazon SNS トピックに送信された完了ステータス受け取ることができない
<a name="video-no-sns-topic"></a>

 Amazon Rekognition Video は、ビデオの分析が完了すると、Amazon SNS トピックにステータス情報を発行します。通常、Amazon SQS キューまたは Lambda 関数を使用してトピックにサブスクライブすることで、完了ステータスメッセージを取得することができます。調査のために、Amazon SNS のトピックを E メールでサブスクライブしておくと、Amazon SNS のトピックに送られたメッセージを E メール受信トレイで受け取ることができます。詳細については、「[Amazon SNS トピックへサブスクライブする](https://docs.aws.amazon.com/sns/latest/dg/sns-create-subscribe-endpoint-to-topic.html)」を参照してください。

アプリケーションでメッセージが受信されない場合は、以下の点を確認します。
+ 分析が完了済みであることを確認します。Get オペレーションレスポンス (`GetLabelDetection` など) の `JobStatus` 値をチェックします。値が `IN_PROGRESS` である場合、分析は未完了であり、完了ステータスは Amazon SNS トピックにまだ発行されていません。
+ Amazon SNS トピックへの発行アクセス許可を Amazon Rekognition Video に付与する IAM サービスロールがあることを確認します。詳細については、「[Amazon Rekognition Video の設定](api-video-roles.md)」を参照してください。
+ 使用している IAM サービスロールでロールの認証情報を使用して Amazon SNS トピックに公開できること、およびサービスロールの許可の範囲が使用中のリソースに安全に設定されていることを確認します。次のステップを実行します。
  + ユーザーの Amazon リソースネーム (ARN) を取得します。

    ```
    aws sts get-caller-identity --profile RekognitionUser 
    ```
  + ロールの信頼関係にユーザー ARN を追加する 詳細については、「[ロールの修正](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage_modify.html)」を参照してください。以下の信頼ポリシー例では、ユーザーのロール認証情報を指定し、サービスロールのアクセス権限を、使用しているリソースのみに制限しています (サービスロールの許可の範囲を安全に制限する方法の詳細については、「[サービス間の混乱した代理の防止](cross-service-confused-deputy-prevention.md)」を参照してください)。
  + ロールを継承します: `aws sts assume-role --role-arn arn:Role ARN --role-session-name SessionName --profile RekognitionUser`
  + Amazon SNS トピックに発行する: `aws sns publish --topic-arn arn:Topic ARN --message "Hello World!" --region us-east-1 --profile RekognitionUser`

   AWS CLI コマンドが機能する場合は、メッセージ (E メールでトピックをサブスクライブしている場合は E メールの受信トレイ) を受け取ります。メッセージが受信されない場合は、以下を行います。
  + Amazon Rekognition Video が設定されていることをチェックします。詳細については、「[Amazon Rekognition Video の設定](api-video-roles.md)」を参照してください。
  + このトラブルシューティングの問いに関する他のヒントを確認します。
+ 正しいAmazon SNS トピックを使用していることをチェックします。
  + 1 つの Amazon SNS トピックへのアクセスを Amazon Rekognition Video に許可する IAM サービスロールを使用している場合は、正しい Amazon SNS トピックに対するアクセス許可を付与したことを確認します。詳細については、「[既存の Amazon SNS トピックへのアクセスをataeruする](api-video-roles.md#api-video-roles-single-topics)」を参照してください。
  + IAM サービスロールを使用して Amazon Rekognition Video に複数の SNS トピックへのアクセスを許可する場合は、正しいトピックを使用しており、トピック名の先頭に [*AmazonRekognition*] が付加されていることを確認します。詳細については、「[複数の Amazon SNS トピックへのアクセスを許可する](api-video-roles.md#api-video-roles-all-topics)」を参照してください。
  +  AWS Lambda 関数を使用する場合は、Lambda 関数が正しい Amazon SNS トピックにサブスクライブされていることを確認します。詳細については、「[Lambda 関数へのファンアウト](https://docs.aws.amazon.com/sns/latest/dg/sns-lambda.html)」を参照してください。
+ Amazon SQS キューを Amazon SNS トピックにサブスクライブする場合は、その Amazon SQS キューにメッセージを送信するアクセス許可が Amazon SNS トピックにあることを確認します。詳細については、[[Amazon SQS キューにメッセージを送信する許可を Amazon SNS トピックに付与する](https://docs.aws.amazon.com/sns/latest/dg/subscribe-sqs-queue-to-sns-topic.html#SendMessageToSQS.sqs.permissions)] を参照してください。

## Amazon SNS トピックのトラブルシューティングに関する追加のヘルプが必要です
<a name="video-troubleshoot-sns"></a>

Amazon SNS AWS X-Ray で を使用して、アプリケーションを通過するメッセージをトレースおよび分析できます。詳細については、[Amazon SNSと AWS X-Ray](https://docs.aws.amazon.com/xray/latest/devguide/xray-services-sns.html)」を参照してください。

その他のヘルプについては、[[Amazon Rekognition フォーラム](https://forums.aws.amazon.com/forum.jspa?forumID=234)] に質問を投稿するか、[[AWS テクニカルサポート](https://aws.amazon.com/premiumsupport/)] へのサインアップを検討してください。