将 Video Intelligence API 与 C# 搭配使用

1. 概览

Google Cloud Video Intelligence API 允许开发者将 Google 视频分析技术用作其应用的一部分。

它可用于:

借助 REST API,用户可以使用整个视频、每个片段、每个镜头和每帧级别的上下文信息为本地存储或 Google Cloud Storage 中存储的视频添加注释。

在此 Codelab 中,您将重点通过 C# 使用 Video Intelligence API。您将学习如何分析视频以获取标签、镜头变化和露骨内容检测。

学习内容

  • 如何使用 Cloud Shell
  • 如何启用 Video Intelligence API
  • 如何对 API 请求进行身份验证
  • 如何安装适用于 C# 的 Google Cloud 客户端库
  • 如何分析视频以获取标签
  • 如何分析视频以获取镜头变化
  • 如何分析视频以进行露骨内容检测

所需条件

  • 一个 Google Cloud Platform 项目
  • 一个浏览器,例如 ChromeFirefox
  • 熟悉 C# 的使用方法

调查问卷

您将如何使用本教程?

仅阅读教程内容 阅读并完成练习

您如何评价自己使用 C# 的体验?

新手水平 中等水平 熟练水平

您如何评价自己在使用 Google Cloud Platform 服务方面的经验水平?

<ph type="x-smartling-placeholder"></ph> 新手 中级 熟练

2. 设置和要求

自定进度的环境设置

  1. 登录 Google Cloud 控制台,然后创建一个新项目或重复使用现有项目。如果您还没有 Gmail 或 Google Workspace 账号,则必须创建一个

295004821bab6a87

37d264871000675d

96d86d3d5655cdbe.png

  • 项目名称是此项目参与者的显示名称。它是 Google API 尚未使用的字符串。您可以随时对其进行更新。
  • 项目 ID 在所有 Google Cloud 项目中是唯一的,并且是不可变的(一经设置便无法更改)。Cloud 控制台会自动生成一个唯一字符串;通常情况下,您无需关注该字符串。在大多数 Codelab 中,您都需要引用项目 ID(通常用 PROJECT_ID 标识)。如果您不喜欢生成的 ID,可以再随机生成一个 ID。或者,您也可以尝试自己的项目 ID,看看是否可用。完成此步骤后便无法更改该 ID,并且此 ID 在项目期间会一直保留。
  • 此外,还有第三个值,即部分 API 使用的项目编号,供您参考。如需详细了解所有这三个值,请参阅文档
  1. 接下来,您需要在 Cloud 控制台中启用结算功能,以便使用 Cloud 资源/API。运行此 Codelab 应该不会产生太多的费用(如果有的话)。若要关闭资源以避免产生超出本教程范围的结算费用,您可以删除自己创建的资源或删除项目。Google Cloud 新用户符合参与 300 美元免费试用计划的条件。

启动 Cloud Shell

虽然可以通过笔记本电脑对 Google Cloud 进行远程操作,但在此 Codelab 中,您将使用 Google Cloud Shell,这是一个在云端运行的命令行环境。

激活 Cloud Shell

  1. 在 Cloud Console 中,点击激活 Cloud Shelld1264ca30785e435.png

cb81e7c8e34bc8d.png

如果这是您第一次启动 Cloud Shell,系统会显示一个中间屏幕,说明它是什么。如果您看到中间屏幕,请点击继续

d95252b003979716.png

预配和连接到 Cloud Shell 只需花几分钟时间。

7833d5e1c5d18f54

这个虚拟机装有所需的所有开发工具。它提供了一个持久的 5 GB 主目录,并在 Google Cloud 中运行,大大增强了网络性能和身份验证功能。您在此 Codelab 中的大部分(即使不是全部)工作都可以通过浏览器完成。

在连接到 Cloud Shell 后,您应该会看到自己已通过身份验证,并且相关项目已设为您的项目 ID。

  1. 在 Cloud Shell 中运行以下命令以确认您已通过身份验证:
gcloud auth list

命令输出

 Credentialed Accounts
ACTIVE  ACCOUNT
*       <my_account>@<my_domain.com>

To set the active account, run:
    $ gcloud config set account `ACCOUNT`
  1. 在 Cloud Shell 中运行以下命令,以确认 gcloud 命令了解您的项目:
gcloud config list project

命令输出

[core]
project = <PROJECT_ID>

如果不是上述结果,您可以使用以下命令进行设置:

gcloud config set project <PROJECT_ID>

命令输出

Updated property [core/project].

3. 启用 Video Intelligence API

您必须先启用 Video Intelligence API,然后才能开始使用该 API。您可以在 Cloud Shell 中使用以下命令启用该 API:

gcloud services enable videointelligence.googleapis.com

4. 安装 C# 版 Google Cloud Video Intelligence API 客户端库

首先,创建一个简单的 C# 控制台应用,用于运行 Video Intelligence API 示例:

dotnet new console -n VideoIntApiDemo

您应该会看到该应用已创建且依赖项已解析:

The template "Console Application" was created successfully.
Processing post-creation actions...
...
Restore succeeded.

接下来,前往 VideoIntApiDemo 文件夹:

cd VideoIntApiDemo/

并将 Google.Cloud.VideoIntelligence.V1 NuGet 软件包添加到项目中:

dotnet add package Google.Cloud.VideoIntelligence.V1
info : Adding PackageReference for package 'Google.Cloud.VideoIntelligence.V1' into project '/home/atameldev/VideoIntApiDemo/VideoIntApiDemo.csproj'.
log  : Restoring packages for /home/atameldev/VideoIntApiDemo/VideoIntApiDemo.csproj...
...
info : PackageReference for package 'Google.Cloud.VideoIntelligence.V1' version '1.0.0' added to file '/home/atameldev/VideoIntApiDemo/VideoIntApiDemo.csproj'.

现在,您可以使用 Video Intelligence API 了!

5. 标签检测

标签分析用于检测本地或 Google Cloud Storage 中存储的视频中的标签。在本部分中,您将分析一个视频,查找存储在 Google Cloud Storage 中的标签。

首先,从 Cloud Shell 的右上角打开代码编辑器:

fd3fc1303e63572.png

找到 VideoIntApiDemo 文件夹内的 Program.cs 文件,并将代码替换为以下代码:

using System;
using System.Collections.Generic;
using Google.Cloud.VideoIntelligence.V1;

namespace VideoIntApiDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = VideoIntelligenceServiceClient.Create();
            var request = new AnnotateVideoRequest
            {
                InputUri = "gs://cloud-samples-data/video/gbikes_dinosaur.mp4",
                Features = { Feature.LabelDetection }
            };
            var op = client.AnnotateVideo(request).PollUntilCompleted();
            foreach (var result in op.Result.AnnotationResults)
            {
                PrintLabels("Video", result.SegmentLabelAnnotations);
                PrintLabels("Shot", result.ShotLabelAnnotations);
                PrintLabels("Frame", result.FrameLabelAnnotations);
            }
        }

        static void PrintLabels(string labelName,
            IEnumerable<LabelAnnotation> labelAnnotations)
        {
            foreach (var annotation in labelAnnotations)
            {
                Console.WriteLine($"{labelName} label: {annotation.Entity.Description}");
                foreach (var entity in annotation.CategoryEntities)
                {
                    Console.WriteLine($"{labelName} label category: {entity.Description}");
                }
                foreach (var segment in annotation.Segments)
                {
                    Console.Write("Segment location: ");
                    Console.Write(segment.Segment.StartTimeOffset);
                    Console.Write(":");
                    Console.WriteLine(segment.Segment.EndTimeOffset);
                    Console.WriteLine($"Confidence: {segment.Confidence}");
                }
            }
        }
    }
}

花一两分钟时间研究一下代码,看看如何为视频添加标签*。*

返回 Cloud Shell,运行应用:

dotnet run

Video Intelligence API 需要几秒钟的时间来提取标签,但最终,您应该会看到以下输出:

Video label: bicycle
Video label category: vehicle
Segment location: "0s":"42.766666s"
Confidence: 0.475821
Video label: tyrannosaurus
Video label category: dinosaur
Segment location: "0s":"42.766666s"
Confidence: 0.4222222
Video label: tree
Video label category: plant
Segment location: "0s":"42.766666s"
Confidence: 0.4231415
...

摘要

在此步骤中,您可以使用 Video Intelligence API 列出视频中的所有标签。如需了解详情,请参阅标签检测页面。

6. 镜头变化检测

您可以使用 Video Intelligence API 来检测本地或 Google Cloud Storage 中存储的视频中的镜头变化。在本部分中,您将对 Google Cloud Storage 中文件的镜头变化执行视频分析。

如需检测镜头变化,请找到 VideoIntApiDemo 文件夹内的 Program.cs 文件,并将代码替换为以下代码:

using System;
using Google.Cloud.VideoIntelligence.V1;

namespace VideoIntApiDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = VideoIntelligenceServiceClient.Create();
            var request = new AnnotateVideoRequest
            {
                InputUri = "gs://cloud-samples-data/video/gbikes_dinosaur.mp4",
                Features = { Feature.ShotChangeDetection }
            };
            var op = client.AnnotateVideo(request).PollUntilCompleted();
            foreach (var result in op.Result.AnnotationResults)
            {
                foreach (var annotation in result.ShotAnnotations)
                {
                    Console.Out.WriteLine("Start Time Offset: {0}\tEnd Time Offset: {1}",
                        annotation.StartTimeOffset, annotation.EndTimeOffset);
                }
            }
        }
    }
}

花一两分钟时间研究一下代码,看看如何执行镜头检测。

返回 Cloud Shell,运行应用。您应该会看到以下输出内容:

dotnet run

您应该会看到以下输出内容:

Start Time Offset: "0s" End Time Offset: "5.166666s"
Start Time Offset: "5.233333s"  End Time Offset: "10.066666s"
Start Time Offset: "10.100s"    End Time Offset: "28.133333s"
Start Time Offset: "28.166666s" End Time Offset: "42.766666s"

摘要

在此步骤中,您可以使用 Video Intelligence API 检测 Google Cloud Storage 中存储的文件中的镜头变化。详细了解镜头更改

7. 露骨内容检测

露骨内容检测用于检测视频中的成人内容。成人内容是指一般适合 18 岁以上人群的内容,包括但不限于裸露画面、性行为和色情内容(包括卡通或动画)。响应包括分桶可能性值,范围为 VERY_UNLIKELY 到 VERY_LIKELY。

当露骨内容检测功能对视频进行评估时,它会逐帧进行评估,并且仅考虑视觉内容。视频的音频部分不用于评估露骨内容级别。

如需检测露骨内容,请找到 VideoIntApiDemo 文件夹内的 Program.cs 文件,并将代码替换为以下代码:

using System;
using Google.Cloud.VideoIntelligence.V1;

namespace VideoIntApiDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = VideoIntelligenceServiceClient.Create();
            var request = new AnnotateVideoRequest
            {
                InputUri = "gs://cloud-samples-data/video/gbikes_dinosaur.mp4",
                Features = { Feature.ExplicitContentDetection }
            };
            var op = client.AnnotateVideo(request).PollUntilCompleted();
            foreach (var result in op.Result.AnnotationResults)
            {
                foreach (var frame in result.ExplicitAnnotation.Frames)
                {
                    Console.WriteLine("Time Offset: {0}", frame.TimeOffset);
                    Console.WriteLine("Pornography Likelihood: {0}", frame.PornographyLikelihood);
                    Console.WriteLine();
                }
            }
        }
    }
}

花一两分钟时间研究一下代码,看看露骨内容检测是如何执行的*。*

返回 Cloud Shell,运行应用:

dotnet run

这可能需要几秒钟,但最终,您应该会看到以下输出:

dotnet run

Time Offset: "0.056149s"
Pornography Likelihood: VeryUnlikely

Time Offset: "1.166841s"
Pornography Likelihood: VeryUnlikely
...
Time Offset: "41.678209s"
Pornography Likelihood: VeryUnlikely

Time Offset: "42.596413s"
Pornography Likelihood: VeryUnlikely

摘要

在此步骤中,您可以使用 Video Intelligence API 对视频执行露骨内容检测。详细了解露骨内容检测

8. 恭喜!

您已了解如何通过 C# 使用 Video Intelligence API!

清理

为避免系统因本快速入门中使用的资源向您的 Google Cloud Platform 账号收取费用,请执行以下操作:

  • 前往 Cloud Platform Console
  • 选择要关停的项目,然后点击“删除”顶部:这会安排删除项目。

了解详情

许可

此作品已获得 Creative Commons Attribution 2.0 通用许可授权。