라벨 감지 가이드

대상

이 튜토리얼은 Video Intelligence API를 탐색하고 애플리케이션 개발을 시작하는 데 도움이 되도록 디자인되었습니다. 이 문서는 Python에 대한 기본 지식이 있는 사람을 대상으로 합니다. 프로그래밍 지식이 부족해도 이 문서를 이해할 수 있습니다. 이 튜토리얼을 마치면 참조 문서를 사용하여 기본적인 애플리케이션을 만들 수 있습니다.

이 튜토리얼에서는 Python 코드를 사용하여 Video Intelligence API 애플리케이션을 설명합니다. 이 튜토리얼의 목적은 Python 클라이언트 라이브러리를 설명하는 것이 아니라 동영상 라벨 인식 기능을 사용하여 Video Intelligence API를 호출하는 방법을 설명하는 것입니다. 자바 및 Node.js로 작성된 애플리케이션도 원리적으로 비슷합니다.

코드만 있는 예시 또는 다른 언어의 예시를 찾으려면 보조 자료인 안내 가이드를 참조하세요.

기본 요건

이 가이드의 기본 요건은 다음과 같습니다.

라벨 인식을 사용하여 동영상에 주석 추가

이 가이드에서는 LABEL_DETECTION 요청을 사용하여 기본 Video API 애플리케이션을 알아봅니다. LABEL_DETECTION 요청은 이미지 콘텐츠에 따라 선택되는 라벨(또는 '태그')로 동영상에 주석을 작성합니다. 예를 들어 교차로를 지나는 기차 차량 동영상은 '기차 차량', '운송', '철도 교차로'와 같은 라벨을 생성할 수 있습니다.

다음은 이 튜토리얼에 필요한 전체 코드입니다. 이 코드에서는 코드의 간략함을 보여주기 위해 대부분의 주석이 삭제되어 있습니다. 이후에 대신 코드를 살펴보는 과정에서 더 많은 주석이 제공됩니다.

import argparse

from google.cloud import videointelligence

def analyze_labels(path):
    """Detects labels given a GCS path."""
    video_client = videointelligence.VideoIntelligenceServiceClient()
    features = [videointelligence.Feature.LABEL_DETECTION]
    operation = video_client.annotate_video(
        request={"features": features, "input_uri": path}
    )
    print("\nProcessing video for label annotations:")

    result = operation.result(timeout=90)
    print("\nFinished processing.")

    segment_labels = result.annotation_results[0].segment_label_annotations
    for i, segment_label in enumerate(segment_labels):
        print("Video label description: {}".format(segment_label.entity.description))
        for category_entity in segment_label.category_entities:
            print(
                "\tLabel category description: {}".format(category_entity.description)
            )

        for i, segment in enumerate(segment_label.segments):
            start_time = (
                segment.segment.start_time_offset.seconds
                + segment.segment.start_time_offset.microseconds / 1e6
            )
            end_time = (
                segment.segment.end_time_offset.seconds
                + segment.segment.end_time_offset.microseconds / 1e6
            )
            positions = "{}s to {}s".format(start_time, end_time)
            confidence = segment.confidence
            print("\tSegment {}: {}".format(i, positions))
            print("\tConfidence: {}".format(confidence))
        print("\n")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument("path", help="GCS file path for label detection.")
    args = parser.parse_args()

    analyze_labels(args.path)

이 간단한 애플리케이션은 다음과 같은 작업을 수행합니다.

  1. 애플리케이션을 실행하는 데 필요한 라이브러리 가져오기
  2. Cloud Storage URI에 저장된 동영상 파일을 인수로 사용해서 main() 함수에 전달합니다.
  3. Video Intelligence API 서비스를 실행하는 데 필요한 사용자 인증 정보를 가져옵니다.
  4. 동영상 서비스로 전송할 동영상 주석 요청을 만듭니다.
  5. 요청을 전송하고 장기 실행 작업을 반환합니다.
  6. 동영상이 처리될 때까지 장기 실행 작업을 반복 실행하고 사용 가능한 값을 반환합니다.
  7. 서비스 응답을 파싱하고 응답을 사용자에게 표시합니다.

라이브러리 가져오기

import argparse

from google.cloud import videointelligence

일부 표준 라이브러리 가져오기: argparse를 가져와 애플리케이션이 입력 파일 이름을 인수로 사용할 수 있도록 하고 sys를 가져와 API 응답을 기다리는 동안 출력 형식을 지정합니다. 몇 가지 간단한 대기 루프를 실행하기 위해 time 패키지를 가져옵니다.

또한 Video Intelligence API를 사용할 때 API 호출 디렉터리를 저장하는 google.cloud.videointelligence_v1 및 해당 열거 클래스를 가져와야 합니다.

애플리케이션 실행

parser = argparse.ArgumentParser(
    description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("path", help="GCS file path for label detection.")
args = parser.parse_args()

analyze_labels(args.path)

여기에서는 동영상 파일 이름의 Google Cloud Storage URI에 대해 전달된 인수를 파싱하고 main() 함수로 전달합니다.

API 인증

Video Intelligence API 서비스와 통신하려면 우선 이전에 획득한 사용자 인증 정보를 사용하여 서비스를 인증해야 합니다. 애플리케이션 내에서 사용자 인증 정보를 얻는 가장 간단한 방법은 애플리케이션 기본 사용자 인증 정보(ADC)를 사용하는 것입니다. 기본적으로 ADC는 GOOGLE_APPLICATION_CREDENTIALS 환경 파일에서 사용자 인증 정보를 얻으려고 시도합니다. 환경 파일은 서비스 계정의 JSON 키 파일을 가리키도록 설정해야 합니다. 빠른 시작에서 ADC를 사용하려면 서비스 계정 및 환경을 설정한 상태여야 합니다.

요청 구성

video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.Feature.LABEL_DETECTION]
operation = video_client.annotate_video(
    request={"features": features, "input_uri": path}
)

이제 Video Intelligence API 서비스가 준비되었으므로 서비스에 대한 요청을 생성할 수 있습니다. Video Intelligence API에 대한 요청은 JSON 객체로 제공됩니다. 이러한 요청의 자세한 구조 정보는 Video Intelligence API 참조를 참조하세요.

이 코드 스니펫은 다음 작업을 수행합니다.

  1. annotate_video() 메서드에 대한 POST 요청을 위해 JSON을 생성합니다.
  2. 전달된 동영상 파일 이름의 Cloud Storage 위치를 요청에 삽입합니다.
  3. annotate 메서드가 LABEL_DETECTION을 수행해야 함을 나타냅니다.

작업 확인

result = operation.result(timeout=90)
print("\nFinished processing.")

기존 작업에 대한 기존 작업 요청을 사용하여 주기적으로 작업 상태를 확인하는 while 루프를 만듭니다. 작업이 done으로 표시되면 응답이 파싱된 것입니다.

응답 파싱

segment_labels = result.annotation_results[0].segment_label_annotations
for i, segment_label in enumerate(segment_labels):
    print("Video label description: {}".format(segment_label.entity.description))
    for category_entity in segment_label.category_entities:
        print(
            "\tLabel category description: {}".format(category_entity.description)
        )

    for i, segment in enumerate(segment_label.segments):
        start_time = (
            segment.segment.start_time_offset.seconds
            + segment.segment.start_time_offset.microseconds / 1e6
        )
        end_time = (
            segment.segment.end_time_offset.seconds
            + segment.segment.end_time_offset.microseconds / 1e6
        )
        positions = "{}s to {}s".format(start_time, end_time)
        confidence = segment.confidence
        print("\tSegment {}: {}".format(i, positions))
        print("\tConfidence: {}".format(confidence))
    print("\n")

작업이 완료되면 요청에 전송된 각 동영상에 대해 하나씩 annotationResults 목록으로 구성되는 AnnotateVideoResponse 내에 응답 결과가 포함됩니다. 요청에 동영상 하나만 전송했기 때문에 첫 번째 결과의 segmentLabelAnnotations를 사용하고 segmentLabelAnnotations의 모든 라벨이 반복됩니다. 이 튜토리얼에서는 segmentLabelAnnotations만 사용하여 동영상 수준의 주석만 표시합니다. 각 segment_label에는 설명(segment_label.description), 항목 카테고리 목록(segment_label.category_entities), 동영상에서 라벨 어커런스의 시작/종료 시간을 식별하는 세그먼트 목록이 포함되어 있습니다. 이 세그먼트는 segment_label_annotations의 경우 전체 동영상을 포함하는 단일 세그먼트 또는 동영상 세그먼트여야 합니다.

{
   "name":"us-west1.12089999971048628582",
   "metadata":{
      "@type":"type.googleapis.com/google.cloud.videointelligence.v1.AnnotateVideoProgress",
      "annotationProgress":[
         {
            "inputUri":"gs://YOUR_BUCKET/YOUR_OBJECT",
            "updateTime":"2020-01-31T01:49:52.498015Z",
            "startTime":"2020-01-31T01:49:43.056481Z"
         }
      ]
   },
   "done": true,
   "response":{
      "@type":"type.googleapis.com/google.cloud.videointelligence.v1.AnnotateVideoResponse",
      "annotationResults":[
         {
            "inputUri":"gs://YOUR_BUCKET/YOUR_OBJECT",
            "segmentLabelAnnotations": [
              {
                "entity": {
                  "entityId": "/m/01yrx",
                  "languageCode": "en-US"
                },
                "segments": [
                  {
                    "segment": {
                      "startTimeOffset": "0s",
                      "endTimeOffset": "14.833664s"
                    },
                    "confidence": 0.98509187
                  }
                ]
              },
               ...
            ]
         }
      ]
   }
}

동영상 하나만 요청에 전송되었기 때문에 첫 번째 결과의 첫 번째 description이 출력됩니다.

애플리케이션 실행

애플리케이션을 실행하려면 단순히 여기에 동영상의 Cloud Storage URI를 전달합니다.

$ python labels.py gs://YOUR_BUCKET/YOUR_OBJECT
Operation us-west1.4757250774497581229 started: 2020-01-30T01:46:30.158989Z
Operation processing ...
The video has been successfully processed.

Video label description: urban area
        Label category description: city
        Segment 0: 0.0s to 38.752016s
        Confidence: 0.946980476379

Video label description: traffic
        Segment 0: 0.0s to 38.752016s
        Confidence: 0.94105899334

Video label description: vehicle
        Segment 0: 0.0s to 38.752016s
        Confidence: 0.919958174229
...
 

출력

아래는 가능한 출력 예시입니다.

Processing video for label annotations:

Finished processing. Video label description: crowd Label category description: people Segment 0: 0.0s to 60.24s Confidence: 0.527720749378

Video label description: official Label category description: person Segment 0: 0.0s to 60.24s Confidence: 0.372822880745

Video label description: audience Label category description: people Segment 0: 0.0s to 60.24s Confidence: 0.501719772816

Video label description: news Segment 0: 0.0s to 60.24s Confidence: 0.867252230644

Video label description: people Label category description: person Segment 0: 0.0s to 60.24s Confidence: 0.46747264266

Video label description: politics Segment 0: 0.0s to 60.24s Confidence: 0.319397002459

수고하셨습니다. Video Intelligence API를 사용하여 주석 작업을 수행했습니다!