동영상에서 객체 추적

모델을 만들어 학습시킨 후 batchPredict 메서드를 사용하여 하나 이상의 동영상에 대한 예측을 요청할 수 있습니다. batchPredict 메서드에 동영상 목록이 포함된 CSV 파일을 제공합니다. batchPredict 메서드는 모델에서 예측하는 객체를 감지하고 추적하여 동영상에 주석을 추가합니다.

모델의 최대 수명은 2년입니다. 2년이 지난 후에도 동영상에 계속 주석을 달려면 새 모델을 만들고 학습시켜야 합니다.

예측 예

AutoML Video Object Tracking에서 일괄 예측을 요청하려면 주석을 추가할 동영상의 Cloud Storage 경로를 나열하는 CSV 파일을 만듭니다. 또한 시작 및 종료 시간을 지정하여 AutoML Video Object Tracking이 동영상의 세그먼트에만 주석을 추가하도록 명령할 수 있습니다. 시작 시간은 0 이상이고 종료 시간보다 이전이어야 합니다. 종료 시간은 시작 시간보다 커야 하고 동영상의 재생 시간보다 작거나 같아야 합니다.

다음 예시에서는 시작 및 종료 시간을 0,inf로 지정하여 전체 동영상에 주석을 추가하는 방법을 보여줍니다.

gs://my-videos-vcm/cow_video.mp4,0,inf
gs://my-videos-vcm/bird_video.mp4,10.00000,15.50000

또한 AutoML Video Object Tracking이 모델의 예측 결과를 기록해야 하는 출력 파일 경로를 지정해야 합니다. 이 경로는 쓰기 권한이 있는 Cloud Storage 버킷 및 객체여야 합니다.

각 동영상의 최대 재생 시간은 3시간이며 최대 파일 크기는 50GB입니다. AutoML Video Object Tracking는 12시간의 처리 시간 안에 약 100시간의 동영상에 대한 예측을 생성할 수 있습니다

웹 UI

  1. AutoML Video Object Tracking UI를 엽니다.
  2. 표시된 목록에서 사용할 모델을 클릭합니다. Cloud Console의 AutoML Video Intelligence 모델 목록
  3. 모델의 테스트 및 사용 탭에서 다음을 수행합니다.
    • 모델 테스트에서 예측에 사용할 CSV 파일을 선택합니다. CSV 파일은 주석을 추가하려는 동영상의 목록을 제공해야 합니다.
    • 또한 모델 테스트에서 주석 처리 결과를 수신할 Cloud Storage 버킷 안의 디렉토리를 선택합니다.

      실제로 Cloud Storage 버킷에 주석 결과를 보관할 특정 'results' 폴더를 만드는 것이 좋습니다.

    • 예측 가져오기를 클릭합니다.
    AutoML Video Intelligence의 예측 요청 구성

예측 가져오기 과정은 주석을 달고자 하는 동영상의 수에 따라 다소 시간이 걸릴 수 있습니다.

이 과정이 완료되면 최근 예측 아래 모델 페이지에 결과가 나타납니다. 결과를 보려면 다음 안내를 따르세요.

  1. 최근 예측 아래의 예측 열에서 확인하려는 예측 옆에 있는 보기를 클릭합니다.
  2. 동영상에서 결과를 보려는 동영상의 이름을 선택합니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • model-id를 모델의 ID로 바꿉니다. ID는 모델 이름의 마지막 요소입니다. 예를 들어 모델 이름이 projects/project-number/locations/location-id/models/VOT6312181905852727296이면 모델 ID는 VOT6312181905852727296가 됩니다.
  • request-id: 이 필드에 디지털 값을 할당합니다.
  • bucket-name을 Cloud Storage 버킷 이름으로 바꿉니다. my-project-vcm).
  • input-file: 주석을 추가할 동영상을 식별하는 CSV 파일 이름으로 바꿉니다.
  • output-storage-path: 예측 결과를 저장할 Cloud Storage 버킷의 경로로 바꿉니다. AutoML Video 객체 추적은 이 경로에 이름이 prediction-model_name-timestamp인 형식을 사용하여 결과에 대한 하위 폴더를 만듭니다. 이 하위 폴더에는 일괄 요청의 각 동영상에 대한 예측 파일이 포함됩니다. 사용자는 이 경로에 대한 쓰기 권한이 있어야 합니다.
  • 참고:
    • project-number: 프로젝트 수입니다.
    • location-id: 주석이 있어야 하는 Cloud 리전입니다. 지원되는 클라우드 리전은 us-east1, us-west1, europe-west1, asia-east1입니다. 리전을 지정하지 않으면 동영상 파일 위치를 기준으로 리전이 결정됩니다.

HTTP 메서드 및 URL:

POST https://automl.googleapis.com/v1beta1/projects/project-number/locations/location-id/models/model-id:batchPredict

JSON 요청 본문:

{
  "request_id": "request-id",
  "inputConfig": {
    "gcsSource": {
      "inputUris": ["gs://bucket-name/input-file.csv"]
    }
  },
  "outputConfig": {
    "gcsDestination": {
      "outputUriPrefix": "gs://output-storage-path"
    }
  },
  "params": {
    "score_threshold": "0.0"
  }
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-number" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://automl.googleapis.com/v1beta1/projects/project-number/locations/location-id/models/model-id:batchPredict"

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-number" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://automl.googleapis.com/v1beta1/projects/project-number/locations/location-id/models/model-id:batchPredict" | Select-Object -Expand Content
모델 학습 작업의 작업 ID를 받아야 합니다. 아래 예시는 모델 학습 작업 ID VOT1741767155885539328이 포함된 응답을 보여줍니다.

Java

AutoML 동영상 객체 추적에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1beta1.BatchPredictInputConfig;
import com.google.cloud.automl.v1beta1.BatchPredictOutputConfig;
import com.google.cloud.automl.v1beta1.BatchPredictRequest;
import com.google.cloud.automl.v1beta1.BatchPredictResult;
import com.google.cloud.automl.v1beta1.GcsDestination;
import com.google.cloud.automl.v1beta1.GcsSource;
import com.google.cloud.automl.v1beta1.ModelName;
import com.google.cloud.automl.v1beta1.OperationMetadata;
import com.google.cloud.automl.v1beta1.PredictionServiceClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

abstract class BatchPredict {

  static void batchPredict() throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    String inputUri = "gs://YOUR_BUCKET_ID/path_to_your_input_csv_or_jsonl";
    String outputUri = "gs://YOUR_BUCKET_ID/path_to_save_results/";
    batchPredict(projectId, modelId, inputUri, outputUri);
  }

  static void batchPredict(String projectId, String modelId, String inputUri, String outputUri)
      throws IOException, ExecutionException, InterruptedException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (PredictionServiceClient client = PredictionServiceClient.create()) {
      // Get the full path of the model.
      ModelName name = ModelName.of(projectId, "us-central1", modelId);

      // Configure the source of the file from a GCS bucket
      GcsSource gcsSource = GcsSource.newBuilder().addInputUris(inputUri).build();
      BatchPredictInputConfig inputConfig =
          BatchPredictInputConfig.newBuilder().setGcsSource(gcsSource).build();

      // Configure where to store the output in a GCS bucket
      GcsDestination gcsDestination =
          GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build();
      BatchPredictOutputConfig outputConfig =
          BatchPredictOutputConfig.newBuilder().setGcsDestination(gcsDestination).build();

      // Build the request that will be sent to the API
      BatchPredictRequest request =
          BatchPredictRequest.newBuilder()
              .setName(name.toString())
              .setInputConfig(inputConfig)
              .setOutputConfig(outputConfig)
              .build();

      // Start an asynchronous request
      OperationFuture<BatchPredictResult, OperationMetadata> future =
          client.batchPredictAsync(request);

      System.out.println("Waiting for operation to complete...");
      future.get();
      System.out.println("Batch Prediction results saved to specified Cloud Storage bucket.");
    }
  }
}

Node.js

AutoML 동영상 객체 추적에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const modelId = 'YOUR_MODEL_ID';
// const inputUri = 'gs://YOUR_BUCKET_ID/path_to_your_input_csv_or_jsonl';
// const outputUri = 'gs://YOUR_BUCKET_ID/path_to_save_results/';

// Imports the Google Cloud AutoML library
const {PredictionServiceClient} = require('@google-cloud/automl').v1beta1;

// Instantiates a client
const client = new PredictionServiceClient();

async function batchPredict() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
    inputConfig: {
      gcsSource: {
        inputUris: [inputUri],
      },
    },
    outputConfig: {
      gcsDestination: {
        outputUriPrefix: outputUri,
      },
    },
  };

  const [operation] = await client.batchPredict(request);

  console.log('Waiting for operation to complete...');
  // Wait for operation to complete.
  const [response] = await operation.promise();
  console.log(
    `Batch Prediction results saved to Cloud Storage bucket. ${response}`
  );
}

batchPredict();

Python

AutoML 동영상 객체 추적에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import automl_v1beta1 as automl


def batch_predict(
    project_id="YOUR_PROJECT_ID",
    model_id="YOUR_MODEL_ID",
    input_uri="gs://YOUR_BUCKET_ID/path/to/your/input/csv_or_jsonl",
    output_uri="gs://YOUR_BUCKET_ID/path/to/save/results/",
):
    """Batch predict"""
    prediction_client = automl.PredictionServiceClient()

    # Get the full path of the model.
    model_full_id = automl.AutoMlClient.model_path(project_id, "us-central1", model_id)

    gcs_source = automl.GcsSource(input_uris=[input_uri])

    input_config = automl.BatchPredictInputConfig(gcs_source=gcs_source)
    gcs_destination = automl.GcsDestination(output_uri_prefix=output_uri)
    output_config = automl.BatchPredictOutputConfig(gcs_destination=gcs_destination)
    params = {}

    request = automl.BatchPredictRequest(
        name=model_full_id,
        input_config=input_config,
        output_config=output_config,
        params=params,
    )
    response = prediction_client.batch_predict(request=request)

    print("Waiting for operation to complete...")
    print(
        "Batch Prediction results saved to Cloud Storage bucket. {}".format(
            response.result()
        )
    )

예측 작업의 상태 가져오기

다음 curl 또는 PowerShell 명령어를 사용하여 일괄 예측 작업의 상태를 쿼리할 수 있습니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

    • project-number: 프로젝트 수입니다.
    • location-id: 주석이 있어야 할 클라우드 리전입니다. 지원되는 클라우드 리전은 us-east1, us-west1, europe-west1, asia-east1입니다. 리전을 지정하지 않으면 동영상 파일 위치를 기준으로 리전이 결정됩니다.
    • operation-id: 작업을 시작할 때 요청으로 생성되고 응답으로 제공된 장기 실행 작업의 ID로 예를 들면 VOT12345....입니다.

HTTP 메서드 및 URL:

GET https://automl.googleapis.com/v1beta1/projects/project-number/locations/location-id/operations/operation-id

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

다음 명령어를 실행합니다.

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-number" \
"https://automl.googleapis.com/v1beta1/projects/project-number/locations/location-id/operations/operation-id"

PowerShell

다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-number" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://automl.googleapis.com/v1beta1/projects/project-number/locations/location-id/operations/operation-id" | Select-Object -Expand Content
operation-name은 AutoML Video Intelligence 객체 추적 API에서 반환하는 작업의 이름입니다. 작업 이름은 projects/project-number/locations/location-id/operations/operation-id 형식입니다.

일괄 예측 작업이 완료되면 명령어에 지정된 Cloud Storage 버킷에 예측 출력이 저장됩니다. 각 동영상 세그먼트에 대한 JSON 파일이 있습니다. JSON 파일의 형식은 my-video-01.avi.json과 같으며 파일 확장자 .json은 원래 파일 이름에 추가됩니다.

{
  "inputUris": ["automl-video-demo-data/sample_video.avi"],
  "object_annotations": [ {
    "annotation_spec": {
      "display_name": "Cat",
      "description": "Cat"
    },
    "confidence": 0.43253016
    "frames": [ {
      "frame": {
        "time_offset": {
          "seconds": 4,
          "nanos": 960000000
        },
        "normalized_bounding_box": {
          "x_min": 0.1,
          "y_min": 0.1,
          "x_max": 0.8,
          "y_max": 0.8
        }
      }
    }, {
      "frame": {
        "time_offset": {
          "seconds": 5,
          "nanos": 960000000
        },
        "normalized_bounding_box": {
          "x_min": 0.2,
          "y_min": 0.2,
          "x_max": 0.9,
          "y_max": 0.9
        }
      }
    } ],
    "segment": {
      "start_time_offset": {
          "seconds": 4,
          "nanos": 960000000
      },
      "end_time_offset": {
          "seconds": 5,
          "nanos": 960000000
      }
    }
  } ],
  "error": {
    "details": [ ]
  }
}