

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 偵測已存放影片中的影片區段
<a name="segments"></a>

Amazon Rekognition Video 提供的 API 可識別有用的影片片段，例如黑框和片尾名單。

觀眾現在觀看的內容比以往都多。特別是，Over-The-Top (OTT) 和隨需影片 (VOD) 平台隨時隨地在任何螢幕上都能提供豐富的內容選擇。隨著內容量不斷增加，媒體公司在準備和管理內容方面面臨挑戰。這對於提供高品質的觀賞體驗和更好的營利內容而言，至關重要。如今，公司使用由訓練有素的人力所組成的大型團隊來執行下列任務。
+ 在一段內容中找到片頭片尾名單的開始位置。
+ 選擇正確的點來插入廣告，例如靜音黑色影格序列
+ 將影片分割成較小的剪輯片段，以便進行索引。

這些手動程序既昂貴又緩慢，而且規模無法跟上每天從封存製作、授權和擷取的內容量。

您可以使用 Amazon Rekognition Video，採用機器學習 (ML) 支援的全受管、專用影片區段偵測 API 來自動執行操作媒體分析任務。透過使用 Amazon Rekognition Video 區段 API，您可以輕鬆分析大量影片，並偵測黑色影格或鏡頭轉換等標記。您可以取得每次偵測的 SMPTE (電影電視工程師協會) 時間碼、時間戳記和影格數量。不需要機器學習經驗。

Amazon Rekognition Video 影片會分析 Amazon Simple Storage Service (Amazon S3) 儲存貯體中存放的影片。Amazon Rekognition Video 傳回的 SMPTE 是影格準確的時間碼：提供偵測到的影片區段精確影格數，並處理各種影片影格播放速率格式。您可以使用來自 Amazon Rekognition Video 的影格準確中繼資料，將特定任務完全自動化，或大幅降低受訓人工操作員的檢閱工作負載，使其可著重在更有創造性的工作。這可讓您執行諸如準備內容、插入廣告以及在雲端中，大規模地將「狂歡標記」新增至內容等任務。

如需定價的相關資訊，請參閱[Amazon Rekognition 定價](https://aws.amazon.com/rekognition/pricing/)。

Amazon Rekognition Video 區段偵測支援兩種類型的分段任務：[技術提示](#segment-technical-cue) 偵測和 [鏡頭偵測](#segment-shot-detection)。

**Topics**
+ [技術提示](#segment-technical-cue)
+ [鏡頭偵測](#segment-shot-detection)
+ [關於 Amazon Rekognition Video 區段偵測 API](#segment-api-intro)
+ [使用 Amazon Rekognition 區段 API](segment-api.md)
+ [範例：偵測已存放影片中的區段](segment-example.md)

## 技術提示
<a name="segment-technical-cue"></a>

*技術提示*可識別影片中的黑色框架、色彩導表、片頭字幕、片尾名單、工作室標誌和主要節目內容。

### 黑色畫面
<a name="segment-black-frame"></a>

影片通常包含一小段無音訊的黑色空白畫面，用作插入廣告或劃定場景或開場演職員表等節目段結尾的提示。借助 Amazon Rekognition Video，您可以偵測此類黑色畫面序列，以自動執行廣告插入、為 VOD 打包內容並劃分各種節目段或場景。帶有音訊的黑色畫面 (例如淡出或旁白) 視為內容，且不會傳回。

### Credits (點數)
<a name="segment-credits"></a>

Amazon Rekognition Video 可幫助您自動識別電影或電視節目片尾名單開始和結束的確切畫面。有了這些資訊，您可以在隨選影片 (VOD) 應用程式中產生「狂歡標記」或互動式檢視器提示，例如「下一集」或「跳過簡介」。您還可以偵測影片中的程序內容的第一幀和最後一幀。Amazon Rekognition Video 經過訓練，可處理各種開始和結束信用風格，從簡單的滾動積分到更具挑戰性的信用以及內容。

### 彩條信號
<a name="segment-color-bar"></a>

Amazon Rekognition Video 讓您可以偵測顯示 SMPTE 彩條信號的影片部分，SMPTE 彩條信號是以特定模式顯示的一組顏色，用於確保顏色在廣播監控器、節目和攝影機上正確校正。如需 SMPTE 彩條信號的詳細資訊，請參閱 [SMPTE 彩條信號](https://en.wikipedia.org/wiki/SMPTE_color_bars)。當彩條信號作為預設信號而不是內容連續顯示時，此中繼資料可用於透過從內容中移除彩條信號來為隨選影片應用程式準備內容，或用於偵測錄製影片中廣播信號遺失等問題。

### 场记板
<a name="segment-slates"></a>

场记板是影片的部分，通常位於開頭附近，其中包含有關單集、工作室、視訊格式、音頻頻道等的文字中繼資料。Amazon Rekognition Video 可以識別场记板的開始和結尾，讓您在準備最終檢視的內容時輕鬆使用文字中繼資料或移除场记板。

### 工作室徽標
<a name="segment-logos"></a>

工作室徽標是顯示參與製作演出的製作工作室的徽標或標誌的序列。Amazon Rekognition Video 可以偵測這些序列，讓使用者可以檢閱其以識別工作室。

### 內容
<a name="segment-content"></a>

內容是電視節目或電影中包含該節目或相關元素的部分。黑色畫面、片頭片尾名單、彩條信號、场记板和工作室徽標不被視為內容。Amazon Rekognition Video 可以偵測影片中每個內容區段的開始和結束，因此您可以找到程式執行時間或特定區段。

內容區段包括但不限於下列專案：
+ 兩個廣告插播之間的程式場景
+ 在影片開始時快速回顧上一集
+ 獎金信用後內容 
+ 「無文字」內容，例如一組原本包含重疊文字的所有程式場景，但已移除文字以支援翻譯成其他語言的所有程式場景。

Amazon Rekognition Video 完成所有內容區段偵測之後，您可以套用網域知識或傳送給人工審查，以進一步分類每個區段。舉例來說，如果您使用的影片一律以回顧開頭，您可以將第一個內容區段歸類為回顧。

下圖說明節目或電影時間軸上的技術提示區段。請注意色彩導表和片頭名單資訊、內容區段 (例如回顧和主要程式)、整個影片中的黑框，以及片尾名單資訊。

![\[顏色列、回顧區段、兩個節目內容區段，以及代表節目或電影時間軸的黑色影格。\]](http://docs.aws.amazon.com/zh_tw/rekognition/latest/dg/images/technical-cue.png)


## 鏡頭偵測
<a name="segment-shot-detection"></a>

鏡頭是由一台攝影機連續拍攝的一系列相互關聯的連續映像，代表在時間和空間上的連續動作。借助 Amazon Rekognition Video，您可以偵測每個鏡頭的開始、結束和持續時間，並可以計算內容中的所有鏡頭。您可以使用任務的鏡頭中繼資料，如下所視。
+ 使用選取的鏡頭製作宣傳影片。
+ 在不會影響觀眾體驗的地方插入廣告，例如，有人說話時的鏡頭中間。
+ 產生一組預覽縮圖，避免鏡頭之間的轉場內容。

鏡頭偵測會標記在對其他相機有硬切換的確切畫面上。如果有從某個攝影機到另一個攝影機的柔性轉場，則 Amazon Rekognition Video 會逸出轉場。如此可確保鏡頭開始與結束時間不包含沒有實際內容的區段。

下圖說明電影底片的鏡頭偵測區段。請注意，從某個相機角度或位置到下一個相機角度的鏡頭來識別每個拍攝畫面。

![\[七個編號的鏡頭，顯示城市街道、汽車儀表板、森林路徑、一個子系、一個小雞、具有攝影師剪影的日落湖。\]](http://docs.aws.amazon.com/zh_tw/rekognition/latest/dg/images/shot-detection.png)


## 關於 Amazon Rekognition Video 區段偵測 API
<a name="segment-api-intro"></a>

若要切分已存放的影片，您可以使用非同步的 [StartSegmentDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartSegmentDetection.html) 和 [GetSegmentDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GetSegmentDetection.html) API，以啟動分鏡任務，並擷取結果。區段偵測可接受存放在 Amazon S3 儲存貯體中的影片，並傳回 JSON 輸出。您可以透過設定 `StartSegmentdetection` API 要求，選擇僅偵測技術提示、僅偵測鏡頭轉換，或兩者兼有。您也可以透過設定最低預測可信度的閾值，來篩選偵測到的區段。如需詳細資訊，請參閱 [使用 Amazon Rekognition 區段 API](segment-api.md)。如需範例程式碼，請參閱 [範例：偵測已存放影片中的區段](segment-example.md)。

# 使用 Amazon Rekognition 區段 API
<a name="segment-api"></a>

Amazon Rekognition Video 中的區段偵測是一種 Amazon Rekognition Video 非同步作業。Amazon Rekognition 區段 API 是一種複合 API，您可以從單一 API 呼叫中選擇分析類型 (技術提示或鏡頭偵測)。如需呼叫非同步操作的詳細資訊，請參閱 [呼叫 Amazon Rekognition Video 操作](api-video.md)。

**Topics**
+ [啟動區段分析](#segment-api-start)
+ [取得區段分析結果](#segment-api-get)

## 啟動區段分析
<a name="segment-api-start"></a>

若要在存放的影片中啟動區段偵測，請呼叫 [StartSegmentDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartSegmentDetection.html)。輸入參數與加入區段類型選擇和結果篩選的其他 Amazon Rekognition Video 操作相同。如需詳細資訊，請參閱 [開始影片分析](api-video.md#api-video-start)。

以下是 `StartSegmentDetection` 傳遞的 JSON 範例。此要求指定同時偵測技術提示和鏡頭偵測區段。針對技術提示區段 (90%) 和鏡頭偵測區段 (80%)，要求使用不同的篩選條件來達到最低偵測可信度。

```
{
  "Video": {
    "S3Object": {
      "Bucket": "test_files",
      "Name": "test_file.mp4"
    }
    "SegmentTypes":["TECHNICAL_CUES", "SHOT"]
    "Filters": {
      "TechnicalCueFilter": {
         "MinSegmentConfidence": 90,
         "BlackFrame" : {
            "MaxPixelThreshold": 0.1,
            "MinCoveragePercentage": 95     
         }
      },
      "ShotFilter" : {
          "MinSegmentConfidence": 60
      }
  }
}
```

### 選擇區段類型
<a name="segment-feature-type"></a>

使用 `SegmentTypes` 陣列輸入參數來偵測輸入影片中的技術提示及/或鏡頭偵測區段。
+ TECHNICAL\$1CUE — 可針對影片中偵測到的片頭、片尾和期間技術提示 (黑條信號、彩色信號、片頭名單、片尾名單、工作室標誌及原節目內容)，識別影格準確的時間戳記。例如，您可以使用技術提示來尋找片尾名單的開頭。如需詳細資訊，請參閱 [技術提示](segments.md#segment-technical-cue)。
+ SHOT：可識別鏡頭的開始、結束和持續時間。例如，您可以使用鏡頭偵測來識別影片最後編輯的候選鏡頭。如需詳細資訊，請參閱 [鏡頭偵測](segments.md#segment-shot-detection)。

### 篩選分析結果
<a name="w2aac43c29b7c11"></a>

您可以使用 `Filters` ([StartSegmentDetectionFilters](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartSegmentDetectionFilters.html)) 輸入參數以指定回應傳回的偵測可信度下限。在中 `Filters`，使用 `ShotFilter` ([StartShotDetectionFilter](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartShotDetectionFilter.html)) 過濾偵測到的鏡頭。使用 `TechnicalCueFilter` ([StartTechnicalCueDetectionFilter](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartTechnicalCueDetectionFilter.html)) 過濾技術提示。

如需範例程式碼，請參閱 [範例：偵測已存放影片中的區段](segment-example.md)。

## 取得區段分析結果
<a name="segment-api-get"></a>

Amazon Rekognition Video 向 Amazon Simple Notification Service 主題發佈影片的完成狀態。如果影片分析成功，您可以呼叫 [GetSegmentDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GetSegmentDetection.html) 取得影片分析的結果。

以下是範例 `GetSegmentDetection` 要求。`JobId` 是呼叫 `StartSegmentDetection` 傳回的任務識別符。如需其他輸入參數的詳細資訊，請參閱 [取得 Amazon Rekognition Video 分析結果](api-video.md#api-video-get)。

```
{
    "JobId": "270c1cc5e1d0ea2fbc59d97cb69a72a5495da75851976b14a1784ca90fc180e3",
    "MaxResults": 10,
    "NextToken": "XfXnZKiyMOGDhzBzYUhS5puM+g1IgezqFeYpv/H/+5noP/LmM57FitUAwSQ5D6G4AB/PNwolrw=="
}
```

`GetSegmentDetection` 會傳回要求的分析結果，以及關於存放影片的一般資訊。

### 一般資訊
<a name="segment-api-general"></a>

`GetSegmentDection` 會傳回以下一般資訊。
+ **音訊資訊**：此回應包含 [AudioMetadata](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_AudioMetadata.html) 物件中的陣列 `AudioMetadata` 的音訊中繼資料。可以有多個音訊串流。每個 `AudioMetadata` 物件都包含單一音訊串流的中繼資料。`AudioMetadata` 物件中的音訊資訊包括音訊轉碼器、音訊聲道的數目、音訊串流的持續時間，以及取樣率。`GetSegmentDetection` 傳回的每一頁資訊中都會傳回音訊中繼資料。
+ **影片資訊**：目前，Amazon Rekognition Video 訊會傳回 `VideoMetadata` 陣列中的單一 [VideoMetadata](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_VideoMetadata.html) 物件。物件包含 Amazon Rekognition Video 選擇要分析之輸入檔案中影片串流的相關資訊。`VideoMetadata` 物件包括影片轉碼器、影片格式，以及其他資訊。`GetSegmentDetection` 傳回的每一頁資訊中都會傳回影片中繼資料。
+ **分頁資訊**：此範例顯示單頁的區段資訊。您可以在 `GetSegmentDetection` 的 `MaxResults` 輸入參數中指定要傳回的元素數目。如果結果數目超過 `MaxResults`，`GetSegmentDetection` 會傳回用來取得下一頁結果的字符 (`NextToken`)。如需詳細資訊，請參閱 [取得 Amazon Rekognition Video 分析結果](api-video.md#api-video-get)。
+ **要求資訊**：呼叫 `StartSegmentDetection` 時要求的分析類型會在 `SelectedSegmentTypes` 欄位中傳回。

### 客群
<a name="segment-api-technical-segments"></a>

影片中偵測到的技術提示和鏡頭資訊會以 [SegmentDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SegmentDetection.html) 物件的陣列 `Segments` 傳回。陣列會依照 `StartSegmentDetection` 之 `SegmentTypes` 輸入參數中指定的區段類型 (技術提示或鏡頭) 排序。在每個區段類型中，陣列會依照時間戳記值排序。每個 `SegmentDetection` 物件都包含偵測到的區段類型 (技術提示或鏡頭偵測) 相關資訊，以及一般資訊，例如，開始時間、結束時間，以及區段的持續時間。

時間資訊會以兩種格式傳回。
+ 

**毫秒**  
影片開始後的毫秒數。欄位 `DurationMillis`、`StartTimestampMillis` 和 `EndTimestampMillis` 的格式為毫秒。
+ 

**時間碼**  
Amazon Rekognition Video 時間碼採用 [SMPTE](https://en.wikipedia.org/wiki/SMPTE_timecode) 格式，其中每個影片影格都有唯一的時間碼值。格式為 *hh:mm:ss:frame*。例如，時間碼值 01:05:40:07 讀為一小時、五分鐘、四十秒和七個影格。Amazon Rekognition Video[影片支援丟棄畫面播放](https://en.wikipedia.org/wiki/SMPTE_timecode#Drop-frame_timecode)速率使用案例。丟棄速率時間碼格式為 *hh:mm:ss;frame*。欄位 `DurationSMPTE`、`StartTimecodeSMPTE` 和 `EndTimecodeSMPTE` 為時間碼格式。
+ 

**影格計數器**  
每個影片片段的持續時間也會以畫面數目來表示。此欄位 `StartFrameNumber` 會在影片片段的開頭 `EndFrameNumber` 在影片片段的結尾提供影格編號。`DurationFrames` 表示影片區段中的影格總數。這些值是使用以 0 開頭的影格索引來計算。

您可以使用 `SegmentType` 欄位來決定 Amazon Rekognition Video 傳回的區段類型。
+ **技術提示**：`TechnicalCueSegment`欄位[是 TechnicalCueSegment](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_TechnicalCueSegment.html) 物件，其包含偵測可信度和技術提示類型。技術提示的類型為 `ColorBars`、`EndCredits`、`BlackFrames`、`OpeningCredits`、`StudioLogo`、`Slate`、和 `Content`。
+ **鏡頭**：`ShotSegment` 欄位是 [ShotSegment](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ShotSegment.html)物件，其包含影片中鏡頭區段的偵測可信度和識別符。

 以下是來自 `GetSegmentDetection` 的 JSON 回應範例。

```
{
    "SelectedSegmentTypes": [
        {
            "ModelVersion": "2.0",
            "Type": "SHOT"
        },
        {
            "ModelVersion": "2.0",
            "Type": "TECHNICAL_CUE"
        }
    ],
    "Segments": [
        {
            "DurationFrames": 299,
            "DurationSMPTE": "00:00:09;29",
            "StartFrameNumber": 0,
            "EndFrameNumber": 299,
            "EndTimecodeSMPTE": "00:00:09;29",
            "EndTimestampMillis": 9976,
            "StartTimestampMillis": 0,
            "DurationMillis": 9976,
            "StartTimecodeSMPTE": "00:00:00;00",
            "Type": "TECHNICAL_CUE",
            "TechnicalCueSegment": {
                "Confidence": 90.45006561279297,
                "Type": "BlackFrames"
            }
        },
        {
            "DurationFrames": 150,
            "DurationSMPTE": "00:00:05;00",
            "StartFrameNumber": 299,
            "EndFrameNumber": 449,
            "EndTimecodeSMPTE": "00:00:14;29",
            "EndTimestampMillis": 14981,
            "StartTimestampMillis": 9976,
            "DurationMillis": 5005,
            "StartTimecodeSMPTE": "00:00:09;29",
            "Type": "TECHNICAL_CUE",
            "TechnicalCueSegment": {
                "Confidence": 100.0,
                "Type": "Content"
            }
        },
        {
            "DurationFrames": 299,
            "ShotSegment": {
                "Index": 0,
                "Confidence": 99.9982681274414
            },
            "DurationSMPTE": "00:00:09;29",
            "StartFrameNumber": 0,
            "EndFrameNumber": 299,
            "EndTimecodeSMPTE": "00:00:09;29",
            "EndTimestampMillis": 9976,
            "StartTimestampMillis": 0,
            "DurationMillis": 9976,
            "StartTimecodeSMPTE": "00:00:00;00",
            "Type": "SHOT"
        },
        {
            "DurationFrames": 149,
            "ShotSegment": {
                "Index": 1,
                "Confidence": 99.9982681274414
            },
            "DurationSMPTE": "00:00:04;29",
            "StartFrameNumber": 300,
            "EndFrameNumber": 449,
            "EndTimecodeSMPTE": "00:00:14;29",
            "EndTimestampMillis": 14981,
            "StartTimestampMillis": 10010,
            "DurationMillis": 4971,
            "StartTimecodeSMPTE": "00:00:10;00",
            "Type": "SHOT"
        }
    ],
    "JobStatus": "SUCCEEDED",
    "VideoMetadata": [
        {
            "Format": "QuickTime / MOV",
            "FrameRate": 29.970029830932617,
            "Codec": "h264",
            "DurationMillis": 15015,
            "FrameHeight": 1080,
            "FrameWidth": 1920,
            "ColorRange": "LIMITED"

        }
    ],
    "AudioMetadata": [
        {
            "NumberOfChannels": 1,
            "SampleRate": 48000,
            "Codec": "aac",
            "DurationMillis": 15007
        }
    ]
}
```

如需範例程式碼，請參閱 [範例：偵測已存放影片中的區段](segment-example.md)。

# 範例：偵測已存放影片中的區段
<a name="segment-example"></a>

下列程序顯示如何偵測存放在 Amazon S3 儲存貯體之影片中的技術提示區段和鏡頭偵測區段。此程序也會示範如何根據 Amazon Rekognition Video 對於偵測準確性的可信度，篩選偵測到的區段。

此範例會展開 [使用 Java 或 Python (SDK) 分析儲存於 Amazon S3 儲存貯體中的影片](video-analyzing-with-sqs.md) 中的程式碼，這會使用 Amazon Simple Queue Service 佇列來取得影片分析要求的完成狀態。

**偵測存放在 Amazon S3 儲存貯體 (SDK) 之影片中的區段**

1. 執行 [使用 Java 或 Python (SDK) 分析儲存於 Amazon S3 儲存貯體中的影片](video-analyzing-with-sqs.md)。

1. 將下列專案新增至您在步驟 1 中使用的程式碼。

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

   1. 新增以下匯入專案。

      ```
      import com.amazonaws.services.rekognition.model.GetSegmentDetectionRequest;
      import com.amazonaws.services.rekognition.model.GetSegmentDetectionResult;
      import com.amazonaws.services.rekognition.model.SegmentDetection;
      import com.amazonaws.services.rekognition.model.SegmentType;
      import com.amazonaws.services.rekognition.model.SegmentTypeInfo;
      import com.amazonaws.services.rekognition.model.ShotSegment;
      import com.amazonaws.services.rekognition.model.StartSegmentDetectionFilters;
      import com.amazonaws.services.rekognition.model.StartSegmentDetectionRequest;
      import com.amazonaws.services.rekognition.model.StartSegmentDetectionResult;
      import com.amazonaws.services.rekognition.model.StartShotDetectionFilter;
      import com.amazonaws.services.rekognition.model.StartTechnicalCueDetectionFilter;
      import com.amazonaws.services.rekognition.model.TechnicalCueSegment;
      import com.amazonaws.services.rekognition.model.AudioMetadata;
      ```

   1. 將下列程式碼新增至類別 `VideoDetect`。

      ```
          //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.)
      
      
          private static void StartSegmentDetection(String bucket, String video) throws Exception{
                  
              NotificationChannel channel= new NotificationChannel()
                      .withSNSTopicArn(snsTopicArn)
                      .withRoleArn(roleArn);
      
              float minTechnicalCueConfidence = 80F; 
              float minShotConfidence = 80F; 
                      
              StartSegmentDetectionRequest req = new StartSegmentDetectionRequest()
                      .withVideo(new Video()
                              .withS3Object(new S3Object()
                                      .withBucket(bucket)
                                      .withName(video)))
                      .withSegmentTypes("TECHNICAL_CUE" , "SHOT")
                      .withFilters(new StartSegmentDetectionFilters()
                              .withTechnicalCueFilter(new StartTechnicalCueDetectionFilter()
                                      .withMinSegmentConfidence(minTechnicalCueConfidence))
                              .withShotFilter(new StartShotDetectionFilter()
                                      .withMinSegmentConfidence(minShotConfidence)))
                      .withJobTag("DetectingVideoSegments")
                      .withNotificationChannel(channel);
      
              StartSegmentDetectionResult startLabelDetectionResult = rek.startSegmentDetection(req);
              startJobId=startLabelDetectionResult.getJobId();
              
          }
      
          private static void GetSegmentDetectionResults() throws Exception{
      
              int maxResults=10;
              String paginationToken=null;
              GetSegmentDetectionResult segmentDetectionResult=null;
              Boolean firstTime=true;
              
      
              do {
                  if (segmentDetectionResult !=null){
                      paginationToken = segmentDetectionResult.getNextToken();
                  }
      
                  GetSegmentDetectionRequest segmentDetectionRequest= new GetSegmentDetectionRequest()
                          .withJobId(startJobId)
                          .withMaxResults(maxResults)
                          .withNextToken(paginationToken);
      
                  segmentDetectionResult = rek.getSegmentDetection(segmentDetectionRequest);
                  
                  if(firstTime) {
                      System.out.println("\nStatus\n------");
                      System.out.println(segmentDetectionResult.getJobStatus());
                      System.out.println("\nRequested features\n------------------");
                       for (SegmentTypeInfo requestedFeatures : segmentDetectionResult.getSelectedSegmentTypes()) {
                          System.out.println(requestedFeatures.getType());
                      }
                       int count=1;
                       List<VideoMetadata> videoMetaDataList = segmentDetectionResult.getVideoMetadata();
                       System.out.println("\nVideo Streams\n-------------");
                       for (VideoMetadata videoMetaData: videoMetaDataList) {
                           System.out.println("Stream: " + count++);
                           System.out.println("\tFormat: " + videoMetaData.getFormat());
                           System.out.println("\tCodec: " + videoMetaData.getCodec());
                           System.out.println("\tDuration: " + videoMetaData.getDurationMillis());
                           System.out.println("\tFrameRate: " + videoMetaData.getFrameRate());
                       } 
      
                       
                       List<AudioMetadata> audioMetaDataList = segmentDetectionResult.getAudioMetadata();
                       System.out.println("\nAudio streams\n-------------");
      
                       count=1;
                       for (AudioMetadata audioMetaData: audioMetaDataList) {
                           System.out.println("Stream: " + count++);
                           System.out.println("\tSample Rate: " + audioMetaData.getSampleRate());
                           System.out.println("\tCodec: " + audioMetaData.getCodec());
                           System.out.println("\tDuration: " + audioMetaData.getDurationMillis());
                           System.out.println("\tNumber of Channels: " + audioMetaData.getNumberOfChannels());
                       }
                       System.out.println("\nSegments\n--------");
      
                      firstTime=false;
                  }
      
      
                  //Show segment information
      
                  List<SegmentDetection> detectedSegments= segmentDetectionResult.getSegments();
                  
                  for (SegmentDetection detectedSegment: detectedSegments) { 
                      
                     if (detectedSegment.getType().contains(SegmentType.TECHNICAL_CUE.toString())) {
                          System.out.println("Technical Cue");
                          TechnicalCueSegment segmentCue=detectedSegment.getTechnicalCueSegment();
                          System.out.println("\tType: " + segmentCue.getType()); 
                          System.out.println("\tConfidence: " + segmentCue.getConfidence().toString());
                      }
                     if (detectedSegment.getType().contains(SegmentType.SHOT.toString())) { 
                          System.out.println("Shot");
                          ShotSegment segmentShot=detectedSegment.getShotSegment();
                          System.out.println("\tIndex " + segmentShot.getIndex()); 
                          System.out.println("\tConfidence: " + segmentShot.getConfidence().toString());
                      }
                      long seconds=detectedSegment.getDurationMillis();
                      System.out.println("\tDuration : " + Long.toString(seconds) + " milliseconds");
                      System.out.println("\tStart time code: " + detectedSegment.getStartTimecodeSMPTE());
                      System.out.println("\tEnd time code: " + detectedSegment.getEndTimecodeSMPTE());
                      System.out.println("\tDuration time code: " + detectedSegment.getDurationSMPTE());
                      System.out.println();
                                      
                   } 
                         
              } while (segmentDetectionResult !=null && segmentDetectionResult.getNextToken() != null);
      
          }
      ```

   1. 在函數 `main` 中，將下行: 

      ```
              StartLabelDetection(amzn-s3-demo-bucket, video);
      
              if (GetSQSMessageSuccess()==true)
              	GetLabelDetectionResults();
      ```

      取代為：

      ```
              StartSegmentDetection(amzn-s3-demo-bucket, video);
      
              if (GetSQSMessageSuccess()==true)
              	GetSegmentDetectionResults();
      ```

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

   ```
   //snippet-start:[rekognition.java2.recognize_video_text.import]
   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.S3Object;
   import software.amazon.awssdk.services.rekognition.model.NotificationChannel;
   import software.amazon.awssdk.services.rekognition.model.Video;
   import software.amazon.awssdk.services.rekognition.model.StartTextDetectionRequest;
   import software.amazon.awssdk.services.rekognition.model.StartTextDetectionResponse;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   import software.amazon.awssdk.services.rekognition.model.GetTextDetectionResponse;
   import software.amazon.awssdk.services.rekognition.model.GetTextDetectionRequest;
   import software.amazon.awssdk.services.rekognition.model.VideoMetadata;
   import software.amazon.awssdk.services.rekognition.model.TextDetectionResult;
   import java.util.List;
   //snippet-end:[rekognition.java2.recognize_video_text.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 DetectVideoSegments {
   
    private static String startJobId ="";
    public static void main(String[] args) {
   
        final String usage = "\n" +
            "Usage: " +
            "   <bucket> <video> <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 video (for example, people.mp4). \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 != 4) {
            System.out.println(usage);
            System.exit(1);
        }
   
        String bucket = args[0];
        String video = args[1];
        String topicArn = args[2];
        String roleArn = args[3];
   
        Region region = Region.US_WEST_2;
        RekognitionClient rekClient = RekognitionClient.builder()
            .region(region)
            .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
            .build();
   
        NotificationChannel channel = NotificationChannel.builder()
            .snsTopicArn(topicArn)
            .roleArn(roleArn)
            .build();
   
        startTextLabels(rekClient, channel, bucket, video);
        GetTextResults(rekClient);
        System.out.println("This example is done!");
        rekClient.close();
    }
   
    // snippet-start:[rekognition.java2.recognize_video_text.main]
    public static void startTextLabels(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();
   
            StartTextDetectionRequest labelDetectionRequest = StartTextDetectionRequest.builder()
                .jobTag("DetectingLabels")
                .notificationChannel(channel)
                .video(vidOb)
                .build();
   
            StartTextDetectionResponse labelDetectionResponse = rekClient.startTextDetection(labelDetectionRequest);
            startJobId = labelDetectionResponse.jobId();
   
        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
   
    public static void GetTextResults(RekognitionClient rekClient) {
   
        try {
            String paginationToken=null;
            GetTextDetectionResponse textDetectionResponse=null;
            boolean finished = false;
            String status;
            int yy=0 ;
   
            do{
                if (textDetectionResponse !=null)
                    paginationToken = textDetectionResponse.nextToken();
   
                GetTextDetectionRequest recognitionRequest = GetTextDetectionRequest.builder()
                    .jobId(startJobId)
                    .nextToken(paginationToken)
                    .maxResults(10)
                    .build();
   
                // Wait until the job succeeds.
                while (!finished) {
                    textDetectionResponse = rekClient.getTextDetection(recognitionRequest);
                    status = textDetectionResponse.jobStatusAsString();
   
                    if (status.compareTo("SUCCEEDED") == 0)
                        finished = true;
                    else {
                        System.out.println(yy + " status is: " + status);
                        Thread.sleep(1000);
                    }
                    yy++;
                }
   
                finished = false;
   
                // Proceed when the job is done - otherwise VideoMetadata is null.
                VideoMetadata videoMetaData=textDetectionResponse.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());
                System.out.println("Job");
   
                List<TextDetectionResult> labels= textDetectionResponse.textDetections();
                for (TextDetectionResult detectedText: labels) {
                    System.out.println("Confidence: " + detectedText.textDetection().confidence().toString());
                    System.out.println("Id : " + detectedText.textDetection().id());
                    System.out.println("Parent Id: " + detectedText.textDetection().parentId());
                    System.out.println("Type: " + detectedText.textDetection().type());
                    System.out.println("Text: " + detectedText.textDetection().detectedText());
                    System.out.println();
                }
   
            } while (textDetectionResponse !=null && textDetectionResponse.nextToken() != null);
   
        } catch(RekognitionException | InterruptedException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
    // snippet-end:[rekognition.java2.recognize_video_text.main]
   }
   ```

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

   1. 將下列程式碼新增至您在步驟 1 中建立的類別 `VideoDetect`。

      ```
      # 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.)
      
          def StartSegmentDetection(self):
      
              min_Technical_Cue_Confidence = 80.0
              min_Shot_Confidence = 80.0
              max_pixel_threshold = 0.1
              min_coverage_percentage = 60
      
              response = self.rek.start_segment_detection(
                  Video={"S3Object": {"Bucket": self.bucket, "Name": self.video}},
                  NotificationChannel={
                      "RoleArn": self.roleArn,
                      "SNSTopicArn": self.snsTopicArn,
                  },
                  SegmentTypes=["TECHNICAL_CUE", "SHOT"],
                  Filters={
                      "TechnicalCueFilter": {
                          "BlackFrame": {
                              "MaxPixelThreshold": max_pixel_threshold,
                              "MinCoveragePercentage": min_coverage_percentage,
                          },
                          "MinSegmentConfidence": min_Technical_Cue_Confidence,
                      },
                      "ShotFilter": {"MinSegmentConfidence": min_Shot_Confidence},
                  }
              )
      
              self.startJobId = response["JobId"]
              print(f"Start Job Id: {self.startJobId}")
      
          def GetSegmentDetectionResults(self):
              maxResults = 10
              paginationToken = ""
              finished = False
              firstTime = True
      
              while finished == False:
                  response = self.rek.get_segment_detection(
                      JobId=self.startJobId, MaxResults=maxResults, NextToken=paginationToken
                  )
      
                  if firstTime == True:
                      print(f"Status\n------\n{response['JobStatus']}")
                      print("\nRequested Types\n---------------")
                      for selectedSegmentType in response['SelectedSegmentTypes']:
                          print(f"\tType: {selectedSegmentType['Type']}")
                          print(f"\t\tModel Version: {selectedSegmentType['ModelVersion']}")
      
                      print()
                      print("\nAudio metadata\n--------------")
                      for audioMetadata in response['AudioMetadata']:
                          print(f"\tCodec: {audioMetadata['Codec']}")
                          print(f"\tDuration: {audioMetadata['DurationMillis']}")
                          print(f"\tNumber of Channels: {audioMetadata['NumberOfChannels']}")
                          print(f"\tSample rate: {audioMetadata['SampleRate']}")
                      print()
                      print("\nVideo metadata\n--------------")
                      for videoMetadata in response["VideoMetadata"]:
                          print(f"\tCodec: {videoMetadata['Codec']}")
                          print(f"\tColor Range: {videoMetadata['ColorRange']}")
                          print(f"\tDuration: {videoMetadata['DurationMillis']}")
                          print(f"\tFormat: {videoMetadata['Format']}")
                          print(f"\tFrame rate: {videoMetadata['FrameRate']}")
                          print("\nSegments\n--------")
      
                      firstTime = False
      
                  for segment in response['Segments']:
      
                      if segment["Type"] == "TECHNICAL_CUE":
                          print("Technical Cue")
                          print(f"\tConfidence: {segment['TechnicalCueSegment']['Confidence']}")
                          print(f"\tType: {segment['TechnicalCueSegment']['Type']}")
      
                      if segment["Type"] == "SHOT":
                          print("Shot")
                          print(f"\tConfidence: {segment['ShotSegment']['Confidence']}")
                          print(f"\tIndex: " + str(segment["ShotSegment"]["Index"]))
      
                      print(f"\tDuration (milliseconds): {segment['DurationMillis']}")
                      print(f"\tStart Timestamp (milliseconds): {segment['StartTimestampMillis']}")
                      print(f"\tEnd Timestamp (milliseconds): {segment['EndTimestampMillis']}")
                      
                      print(f"\tStart timecode: {segment['StartTimecodeSMPTE']}")
                      print(f"\tEnd timecode: {segment['EndTimecodeSMPTE']}")
                      print(f"\tDuration timecode: {segment['DurationSMPTE']}")
      
                      print(f"\tStart frame number {segment['StartFrameNumber']}")
                      print(f"\tEnd frame number: {segment['EndFrameNumber']}")
                      print(f"\tDuration frames: {segment['DurationFrames']}")
      
                      print()
      
                  if "NextToken" in response:
                      paginationToken = response["NextToken"]
                  else:
                      finished = True
      ```

   1. 在函數 `main` 中，將下行:

      ```
          analyzer.StartLabelDetection()
          if analyzer.GetSQSMessageSuccess()==True:
              analyzer.GetLabelDetectionResults()
      ```

      取代為：

      ```
          analyzer.StartSegmentDetection()
          if analyzer.GetSQSMessageSuccess()==True:
              analyzer.GetSegmentDetectionResults()
      ```

------
**注意**  
如果您已執行 [使用 Java 或 Python (SDK) 分析儲存於 Amazon S3 儲存貯體中的影片](video-analyzing-with-sqs.md) 以外的影片範例，要取代的程式碼可能會不同。

1. 執行程式碼。隨即顯示在輸入影片中偵測到的區段相關資訊。