動画内オブジェクトのトラッキング

モデルの作成(トレーニング)が済んだら、batchPredict メソッドを使用して動画の予測をリクエストできます。動画のリストを含む CSV ファイルを batchPredict メソッドに渡します。batchPredict メソッドでは、モデルによって予測されたオブジェクトの検出とトラッキングを行うことで、動画にアノテーションが付けられます。

モデルの最大寿命は 2 年です。2 年経つと、動画にアノテーションを付けるには、新しいモデルを作成してトレーニングする必要が生じます。

予測の例

AutoML Video Object Tracking にバッチ予測をリクエストするには、アノテーションを付ける動画への Cloud Storage パスをリストした CSV ファイルを作成します。開始時間と終了時間を指定して、動画のセグメントにのみアノテーションを付けるよう AutoML Video Object Tracking に指示することもできます。開始時間はゼロ以上で、終了時間より前にする必要があります。終了時間は開始時間より後で、動画の長さ以下にする必要があります。

次の例は、開始時間と終了時間を 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 時間までで、最大ファイルサイズは 50 GB です。AutoML Video Object Tracking では、12 時間の処理時間で約 100 時間分の動画の予測を生成できます。

ウェブ UI

  1. AutoML Video Object Tracking UI を開きます。
  2. 表示されたリストから、使用するモデルをクリックします。Cloud Console での AutoML Video Intelligence モデルのリスト
  3. モデルの [テストと使用] タブで次の操作を行います。
    • [モデルのテスト] で、予測に使用する CSV ファイルを選択します。この CSV ファイルには、アノテーションを付ける動画のリストが含まれている必要があります。
    • [Test your model] ではさらに、アノテーション結果を受け取る Cloud Storage バケット内のディレクトリを選択します。

      アノテーション結果を保持する特定の結果フォルダを Cloud Storage バケットに実際に作成してもかまいません。

    • [Get Predictions] をクリックします。
    AutoML Video Intelligence に対する予測リクエストを構成する

アノテーションを付ける動画の数によっては、予測を取得する処理に時間がかかることがあります。

処理が完了すると、モデルページの [Recent Predictions] の下に結果が表示されます。 結果を見るには、次の手順に従います。

  1. [Recent Predictions] の [Predictions] 列で、表示する予測の [View] をクリックします。
  2. [Video] で、結果を表示する動画の名前を選択します。

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 Object Tracking は、prediction-model_name-timestamp という形式でこのパスに結果のサブフォルダを作成します。このサブフォルダには、バッチ リクエスト内の各動画の予測ファイルが格納されます。このパスへの書き込み権限が必要です。
  • 注:
    • project-number: プロジェクトの番号。
    • location-id: アノテーションを実行する Cloud リージョン。サポート対象のクラウド リージョンは us-east1us-west1europe-west1asia-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 Video Object Tracking への認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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 Video Object Tracking への認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

/**
 * 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 Video Object Tracking への認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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: アノテーションを実行する Cloud リージョン。サポート対象のクラウド リージョンは us-east1us-west1europe-west1asia-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 Object Tracking 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": [ ]
  }
}