检测视频中的露骨内容

露骨内容检测功能可检测视频中的成人内容。成人内容通常不适合 18 岁以下人士,包括但不限于裸露画面、性行为和色情内容。此外,我们还会识别在卡通或动画中检测到的此类内容。

响应包括分区化可能性值,范围为 VERY_UNLIKELYVERY_LIKELY

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

以下示例展示如何对 Cloud Storage 中的文件执行视频分析以获取露骨内容检测特征。

REST

发送视频注释请求

下面演示了如何向 videos:annotate 方法发送 POST 请求。该示例使用 Google Cloud CLI 创建访问令牌。如需了解如何安装 gcloud CLI,请参阅 Video Intelligence API 快速入门

在使用任何请求数据之前,请先进行以下替换:

  • INPUT_URI:包含要添加注释的文件的 Cloud Storage 存储分区(包括文件名)。必须以 gs:// 开头。
    例如:"inputUri": "gs://cloud-videointelligence-demo/assistant.mp4",
  • PROJECT_NUMBER:您的 Google Cloud 项目的数字标识符

HTTP 方法和网址:

POST https://videointelligence.googleapis.com/v1/videos:annotate

请求 JSON 正文:

{
  "inputUri": "INPUT_URI",
  "features": ["EXPLICIT_CONTENT_DETECTION"]
}

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/operations/OPERATION_ID"
}

如果响应成功,Video Intelligence API 将返回您的操作的 name。上面显示了此类响应的示例,其中:

  • PROJECT_NUMBER:您项目的编号
  • LOCATION_ID:在其中添加注释的 Cloud 区域。支持的云区域为:us-east1us-west1europe-west1asia-east1。如果未指定区域,系统将根据视频文件位置确定区域。
  • OPERATION_ID:是为请求创建的长时间运行的操作的 ID,并在启动操作时在响应中提供,例如 12345...

获取注释结果

如需检索操作的结果,请使用从 videos:annotate 调用返回的操作名称发出 GET 请求,如以下示例所示。

在使用任何请求数据之前,请先进行以下替换:

  • OPERATION_NAME:Video Intelligence API 返回的操作名称。操作名称采用 projects/PROJECT_NUMBER/locations/LOCATION_ID/operations/OPERATION_ID 格式
  • PROJECT_NUMBER:您的 Google Cloud 项目的数字标识符

HTTP 方法和网址:

GET https://videointelligence.googleapis.com/v1/OPERATION_NAME

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.videointelligence.v1.AnnotateVideoProgress",
    "annotationProgress": [
     {
      "inputUri": "/demomaker/gbikes_dinosaur.mp4",
      "progressPercent": 100,
      "startTime": "2020-03-26T00:16:35.112404Z",
      "updateTime": "2020-03-26T00:16:55.937889Z"
     }
    ]
   },
   "done": true,
   "response": {
    "@type": "type.googleapis.com/google.cloud.videointelligence.v1.AnnotateVideoResponse",
    "annotationResults": [
     {
      "inputUri": "/demomaker/gbikes_dinosaur.mp4",
      "explicitAnnotation": {
       "frames": [
        {
         "timeOffset": "0.056149s",
         "pornographyLikelihood": "VERY_UNLIKELY"
        },
        {
         "timeOffset": "1.166841s",
         "pornographyLikelihood": "VERY_UNLIKELY"
        },
            ...
        {
         "timeOffset": "41.678209s",
         "pornographyLikelihood": "VERY_UNLIKELY"
        },
        {
         "timeOffset": "42.596413s",
         "pornographyLikelihood": "VERY_UNLIKELY"
        }
       ]
      }
     }
    ]
   }
  }
镜头检测注释以 shotAnnotations 列表的形式返回。 注意:仅当值为 True 时,才会返回 done 字段。操作未完成的响应中不包含该字段。

下载注释结果

将来源中的注释复制到目标存储分区(请参阅复制文件和对象):

gcloud storage cp gcs_uri gs://my-bucket

注意:如果输出 gcs uri 由用户提供,则注释存储在该 gcs uri 中。

Go


func explicitContentURI(w io.Writer, file string) error {
	ctx := context.Background()
	client, err := video.NewClient(ctx)
	if err != nil {
		return err
	}
	defer client.Close()

	op, err := client.AnnotateVideo(ctx, &videopb.AnnotateVideoRequest{
		Features: []videopb.Feature{
			videopb.Feature_EXPLICIT_CONTENT_DETECTION,
		},
		InputUri: file,
	})
	if err != nil {
		return err
	}
	resp, err := op.Wait(ctx)
	if err != nil {
		return err
	}

	// A single video was processed. Get the first result.
	result := resp.AnnotationResults[0].ExplicitAnnotation

	for _, frame := range result.Frames {
		offset, _ := ptypes.Duration(frame.TimeOffset)
		fmt.Fprintf(w, "%s - %s\n", offset, frame.PornographyLikelihood.String())
	}

	return nil
}

Java

如需向 Video Intelligence 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

// Instantiate a com.google.cloud.videointelligence.v1.VideoIntelligenceServiceClient
try (VideoIntelligenceServiceClient client = VideoIntelligenceServiceClient.create()) {
  // Create an operation that will contain the response when the operation completes.
  AnnotateVideoRequest request =
      AnnotateVideoRequest.newBuilder()
          .setInputUri(gcsUri)
          .addFeatures(Feature.EXPLICIT_CONTENT_DETECTION)
          .build();

  OperationFuture<AnnotateVideoResponse, AnnotateVideoProgress> response =
      client.annotateVideoAsync(request);

  System.out.println("Waiting for operation to complete...");
  // Print detected annotations and their positions in the analyzed video.
  for (VideoAnnotationResults result : response.get().getAnnotationResultsList()) {
    for (ExplicitContentFrame frame : result.getExplicitAnnotation().getFramesList()) {
      double frameTime =
          frame.getTimeOffset().getSeconds() + frame.getTimeOffset().getNanos() / 1e9;
      System.out.printf("Location: %.3fs\n", frameTime);
      System.out.println("Adult: " + frame.getPornographyLikelihood());
    }
  }

Node.js

如需向 Video Intelligence 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

// Imports the Google Cloud Video Intelligence library
const video = require('@google-cloud/video-intelligence').v1;

// Creates a client
const client = new video.VideoIntelligenceServiceClient();

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const gcsUri = 'GCS URI of video to analyze, e.g. gs://my-bucket/my-video.mp4';

const request = {
  inputUri: gcsUri,
  features: ['EXPLICIT_CONTENT_DETECTION'],
};

// Human-readable likelihoods
const likelihoods = [
  'UNKNOWN',
  'VERY_UNLIKELY',
  'UNLIKELY',
  'POSSIBLE',
  'LIKELY',
  'VERY_LIKELY',
];

// Detects unsafe content
const [operation] = await client.annotateVideo(request);
console.log('Waiting for operation to complete...');
const [operationResult] = await operation.promise();
// Gets unsafe content
const explicitContentResults =
  operationResult.annotationResults[0].explicitAnnotation;
console.log('Explicit annotation results:');
explicitContentResults.frames.forEach(result => {
  if (result.timeOffset === undefined) {
    result.timeOffset = {};
  }
  if (result.timeOffset.seconds === undefined) {
    result.timeOffset.seconds = 0;
  }
  if (result.timeOffset.nanos === undefined) {
    result.timeOffset.nanos = 0;
  }
  console.log(
    `\tTime: ${result.timeOffset.seconds}` +
      `.${(result.timeOffset.nanos / 1e6).toFixed(0)}s`
  );
  console.log(
    `\t\tPornography likelihood: ${likelihoods[result.pornographyLikelihood]}`
  );
});

Python

如需详细了解如何安装和使用 Python 版 Cloud Video Intelligence API 客户端库,请参阅 Cloud Video Intelligence API 客户端库
"""Detects explicit content from the GCS path to a video."""
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.Feature.EXPLICIT_CONTENT_DETECTION]

operation = video_client.annotate_video(
    request={"features": features, "input_uri": path}
)
print("\nProcessing video for explicit content annotations:")

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

# Retrieve first result because a single video was processed
for frame in result.annotation_results[0].explicit_annotation.frames:
    likelihood = videointelligence.Likelihood(frame.pornography_likelihood)
    frame_time = frame.time_offset.seconds + frame.time_offset.microseconds / 1e6
    print("Time: {}s".format(frame_time))
    print("\tpornography: {}".format(likelihood.name))

其他语言

C#:请按照客户端库页面上的 C# 设置说明操作,然后访问 .NET 版 Video Intelligence 参考文档。

PHP:请按照客户端库页面上的 PHP 设置说明操作,然后访问 PHP 版 Video Intelligence 参考文档

Ruby:请按照客户端库页面上的 Ruby 设置说明操作,然后访问 Ruby 版 Video Intelligence 参考文档