跟踪视频中的对象

创建(训练)完模型后,您可以使用 batchPredict 方法请求对一个或多个视频执行预测。您可以为 batchPredict 方法提供包含一系列视频的 CSV 文件batchPredict 方法通过检测和跟踪模型预测的对象为视频加注释。

模型的最长使用期限为两年。两年后,您必须创建并训练新模型,才能继续为视频添加注释。

预测示例

要从 AutoML Video 对象跟踪请求批量预测,请创建一个 CSV 文件,在其中列出了您要添加注释的视频的 Cloud Storage 路径。您还可以指定开始时间和结束时间,指示 AutoML Video 对象跟踪仅对一段视频添加注释。开始时间必须等于或大于零,必须早于结束时间。结束时间必须晚于开始时间,并且必须小于或等于视频的时长。

以下示例展示了如何通过将开始时间和结束时间指定为 0,inf 来为整个视频添加注释。

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

您还必须指定输出文件路径,AutoML Video 对象跟踪会将您模型的预测结果写到该路径下。该路径必须是您有写入权限的 Cloud Storage 存储桶和对象。

每个视频的时长最长可达 3 小时,文件大小上限为 50GB。 AutoML Video 对象跟踪可以在 12 小时内为大约 100 小时的视频生成预测。

网页界面

  1. 打开 AutoML Video 对象跟踪界面
  2. 从显示的列表中点击要使用的模型。Cloud 控制台中的 AutoML Video Intelligence 模型列表
  3. 在模型的测试和使用标签页上,执行以下操作:
    • 测试您的模型下,选择要用于预测的 CSV 文件。CSV 文件必须提供要添加注释的视频的列表
    • 此外,在测试模型下,选择 Cloud Storage 存储桶中的一个目录以接收注解结果。

      实际上,您可能想要在 Cloud Storage 存储桶中创建一个特定的“结果”文件夹以用于保存注解结果。

    • 点击获取预测
    配置 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-east1us-west1europe-west1asia-east1。如果未指定区域,系统将根据视频文件位置确定区域。

HTTP 方法和网址:

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 对象跟踪进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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 对象跟踪进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * 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 对象跟踪进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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 方法和网址:

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": [ ]
  }
}