

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 저장된 비디오에서 비디오 세그먼트 감지
<a name="segments"></a>

Amazon Rekognition Video는 블랙 프레임 및 엔드 크레딧과 같은 유용한 비디오 세그먼트를 식별하는 API를 제공합니다.

시청자들은 그 어느 때보다 많은 콘텐츠를 보고 있습니다. 특히 OTT(Over-The-Top) 및 VOD(온디맨드 비디오) 플랫폼을 통해 언제 어디서나 어떤 화면에서든 다양한 콘텐츠를 선택할 수 있습니다. 콘텐츠의 양이 급증하면서 미디어 기업들은 콘텐츠를 준비하고 관리하는 데 어려움을 겪고 있습니다. 콘텐츠 준비와 관리는 고품질의 시청 환경을 제공하고 더 나은 콘텐츠로 수익을 창출하는 데 매우 중요합니다. 오늘날 기업은 관련 교육을 이수한 대규모 인력 팀을 통해 다음과 같은 태스크를 수행하고 있습니다.
+ 콘텐츠 내에서 오프닝 및 엔딩 크레딧 위치 찾기
+ 광고를 삽입할 적절한 지점 선택(예: 무음 블랙 프레임 시퀀스)
+ 더 나은 인덱싱을 위해 비디오를 작은 클립으로 분할

이러한 수작업 프로세스는 비용이 많이 들고 속도가 느릴 뿐만 아니라 매일 아카이브에서 생성, 라이선싱 및 검색되는 콘텐츠 양에 맞추어 규모를 조정할 수 없습니다.

Amazon Rekognition Video를 사용하면 기계 학습(ML)으로 구동되는 완전 관리형 전용 비디오 세그먼트 탐지 API를 사용하여 운영 미디어 분석 작업을 자동화할 수 있습니다. Amazon Rekognition Video 세그먼트 API를 사용하면 대량의 비디오를 손쉽게 분석하고 블랙 프레임이나 샷 전환 등의 마커를 감지할 수 있습니다. 각 감지에 대해 SMPTE(Society of Motion Picture and Television Engineers) 타임코드, 타임스탬프 및 프레임 번호가 생성됩니다. ML 경험은 필요하지 않습니다.

Amazon Rekognition Video는 Amazon Simple Storage Service(S3) 버킷에 저장된 동영상을 분석합니다. 반환되는 SMPTE 타임코드는 프레임 단위의 정밀성을 갖추고 있습니다. Amazon Rekognition Video는 감지된 비디오 세그먼트의 정확한 프레임 번호를 제공하고 다양한 비디오 프레임 속도 형식을 자동으로 처리합니다. 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 Segment 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는 영화 또는 TV 프로그램에서 오프닝 및 엔딩 크레딧이 시작하고 끝나는 정확한 프레임을 자동으로 식별할 수 있습니다. 이 정보를 사용하여 VOD(비디오 온 디맨드) 애플리케이션의 비디오 내에 '다음 에피소드' 또는 '인트로 건너뛰기'와 같은 '몰아보기 마커' 또는 대화형 시청자 프롬프트를 생성할 수 있습니다. 비디오 내 프로그램 콘텐츠의 첫 번째 프레임과 마지막 프레임도 감지할 수 있습니다. Amazon Rekognition Video는 간단한 롤링 크레딧부터 콘텐츠와 함께 제공되는 더 까다로운 크레딧에 이르기까지 다양한 오프닝 및 엔딩 크레딧 스타일을 처리하도록 훈련되었습니다.

### 색상 막대
<a name="segment-color-bar"></a>

Amazon Rekognition Video를 사용하면 브로드캐스트 모니터, 프로그램 및 카메라에서 색상이 올바르게 보정되도록 특정 패턴으로 표시되는 색상 세트인 SMPTE 색상 막대를 표시하는 비디오 섹션을 감지할 수 있습니다. SMPTE 색상 막대에 대한 자세한 내용은 [SMPTE 색상 막대](https://en.wikipedia.org/wiki/SMPTE_color_bars)를 참조하십시오. 이 메타데이터는 콘텐츠에서 색상 막대 세그먼트를 제거하여 VOD 애플리케이션용 콘텐츠를 준비하거나 색상 막대가 콘텐츠 대신 기본 신호로 계속 표시될 때 녹화에서 브로드캐스트 신호 손실과 같은 문제를 감지하는 데 유용합니다.

### 슬레이트
<a name="segment-slates"></a>

슬레이트는 일반적으로 시작 부분에 가까운 비디오 섹션으로, 에피소드, 스튜디오, 비디오 형식, 오디오 채널 등에 대한 텍스트 메타데이터를 포함합니다. Amazon Rekognition Video는 슬레이트의 시작과 끝을 식별할 수 있으므로 텍스트 메타데이터를 사용하거나 최종 시청을 위해 콘텐츠를 준비할 때 슬레이트를 제거하는 것이 쉽습니다.

### 스튜디오 로고
<a name="segment-logos"></a>

스튜디오 로고는 프로그램 제작에 참여한 프로덕션 스튜디오의 로고나 엠블럼을 보여주는 시퀀스입니다. Amazon Rekognition Video는 사용자가 검토를 통해 스튜디오를 식별할 수 있도록 이런 시퀀스를 감지합니다.

### 내용
<a name="segment-content"></a>

콘텐츠는 TV 프로그램 또는 영화에서 프로그램 또는 관련 요소가 포함된 부분입니다. 블랙 프레임, 크레딧, 색상 막대, 슬레이트, 스튜디오 로고는 콘텐츠로 간주되지 않습니다. Amazon Rekognition Video는 비디오에 있는 각 콘텐츠 세그먼트의 시작과 끝을 감지할 수 있으므로 사용자가 프로그램의 런타임 또는 특정 세그먼트를 찾을 수 있습니다.

콘텐츠 세그먼트는 다음이 포함되지만 이에 제한되지는 않습니다.
+ 두 개의 광고 시간 사이에 들어가는 프로그램 장면
+ 비디오 시작 부분에 나오는 이전 에피소드의 간단한 요약
+ 크레딧 뒤에 나오는 보너스 콘텐츠 
+ ‘텍스트가 없는’ 콘텐츠, 예를 들어 원래는 오버레이된 텍스트가 있었지만 다른 언어로 번역을 지원하기 위해 텍스트가 제거되어 있는 모든 프로그램 장면의 집합

Amazon Rekognition Video에서 모든 콘텐츠 세그먼트 탐지를 완료한 후에는 도메인 지식을 적용하거나 사람이 검토할 수 있도록 보내서 각 세그먼트를 추가로 분류할 수 있습니다. 예를 들어 사용자의 비디오가 항상 지난 에피소드 요약으로 시작한다면 첫 번째 콘텐츠 세그먼트를 요약으로 분류할 수 있습니다.

다음 다이어그램은 프로그램 또는 영화 타임라인의 기술적 큐 세그먼트를 보여 줍니다. 색상 막대와 오프닝 크레딧, 요약 및 메인 프로그램과 같은 콘텐츠 세그먼트, 동영상 전체의 검은색 프레임, 최종 크레딧이 있는 것을 확인하세요.

![\[색상 막대, 요약 세그먼트, 프로그램 콘텐츠 세그먼트 2개, 쇼 또는 영화 타임라인을 나타내는 검은색 프레임.\]](http://docs.aws.amazon.com/ko_kr/rekognition/latest/dg/images/technical-cue.png)


## 샷 감지
<a name="segment-shot-detection"></a>

샷은 하나의 카메라로 연속 촬영한 서로 연결된 일련의 사진으로 시간과 공간에서 연속적인 동작을 나타냅니다. Amazon Rekognition Video를 사용하면 각 샷의 시작, 종료 및 재생 시간을 감지할 수 있을 뿐만 아니라 콘텐츠의 모든 샷을 셀 수 있습니다. 다음과 같은 태스크에 샷 메타데이터를 사용할 수 있습니다.
+ 선택한 샷을 사용하여 프로모션 비디오 생성
+ 샷 중간에 누군가가 말을 할 때와 같이 시청자의 경험을 방해하지 않는 위치에 광고 삽입 
+ 샷 간의 전환 콘텐츠를 방지하는 미리 보기 썸네일 세트 생성

샷 감지는 다른 카메라로의 확실한 전환이 있는 정확한 프레임에 표시됩니다. 한 카메라에서 다른 카메라로 부드럽게 전환되는 경우 Amazon Rekognition Video는 해당 전환을 생략합니다. 이를 통해 샷 시작 및 종료 시간에 실제 콘텐츠가 없는 섹션이 포함되지 않습니다.

다음 다이어그램은 필름 스트립의 샷 감지 세그먼트를 보여줍니다. 각 샷은 한 카메라 각도 또는 위치에서 다음 각도 또는 위치로 전환하는 것을 통해 식별됩니다.

![\[도시 거리, 자동차 대시보드, 숲길, 어린이, 새끼 병아리, 사진작가 실루엣이 있는 일몰 호수를 보여주는 7개 번호가 매겨진 사진.\]](http://docs.aws.amazon.com/ko_kr/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 Segment API 사용](segment-api.md) 단원을 참조하십시오. 예제 코드는 [예제: 저장된 비디오에서 세그먼트 감지](segment-example.md) 항목을 참조하세요.

# Amazon Rekognition Segment API 사용
<a name="segment-api"></a>

Amazon Rekognition Video의 저장된 비디오 속 얼굴 감지는 Amazon Rekognition Video 비동기 작업입니다. Amazon Rekognition Segment 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` 필드에 반환됩니다.

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

비디오에서 감지된 기술적 큐와 샷 정보는 [SegmentDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SegmentDetection.html) 객체의 `Segments` 배열에 반환됩니다. 배열은 `StartSegmentDetection`의 `SegmentTypes` 입력 파라미터에 지정된 세그먼트 유형(TECHICAL\$1CUE 또는 SHOT)을 기준으로 정렬됩니다. 각 세그먼트 유형 내에서 배열은 타임스탬프 값으로 정렬됩니다. 각 `SegmentDetection` 객체에는 감지된 세그먼트 유형(기술적 큐 또는 샷 감지)에 대한 정보와 세그먼트 시작 시간, 종료 시간 및 재생 시간과 같은 일반 정보가 포함됩니다.

시간 정보는 세 가지 형식으로 반환됩니다.
+ 

**밀리초**  
비디오가 시작된 이후 경과한 시간(밀리초)입니다. `DurationMillis`, `StartTimestampMillis` 및 `EndTimestampMillis` 필드는 밀리초 형식입니다.
+ 

**타임코드**  
Amazon Rekognition Video 타임코드는 각 비디오 프레임에 고유한 타임코드 값이 있는 [SMPTE](https://en.wikipedia.org/wiki/SMPTE_timecode) 형식으로, *hh:mm:ss:frame* 형식을 갖습니다. 예를 들어 타임코드 값이 01:05:40:07이면 1시간, 5분, 40초, 7개 프레임을 의미합니다. 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가 감지 정확성에 대해 갖는 신뢰도를 기반으로 감지된 세그먼트를 필터링하는 방법도 보여 줍니다.

이 예제는 Amazon Simple Queue Service 대기열을 사용하여 비디오 분석 요청의 완료 상태를 가져오는 [Java 또는 Python으로 Amazon S3 버킷에 저장된 비디오 분석(SDK)](video-analyzing-with-sqs.md)의 코드를 확장합니다.

**Amazon S3 버킷에 저장된 비디오에서 세그먼트를 감지하려면(SDK)**

1. [Java 또는 Python으로 Amazon S3 버킷에 저장된 비디오 분석(SDK)](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으로 Amazon S3 버킷에 저장된 비디오 분석(SDK)](video-analyzing-with-sqs.md) 이외에 비디오 예제를 이미 실행한 경우, 바꿀 코드가 다를 수 있습니다.

1. 코드를 실행합니다. 입력 비디오에서 감지된 세그먼트에 대한 정보가 표시됩니다.