了解 Android NDK 上的用户环境 (C)

了解如何在您自己的应用中使用 Scene Semantics API

借助 Scene Semantics API,开发者能够提供基于机器学习模型的实时语义信息,了解用户周围的场景。给定户外场景图像后,该 API 会针对一组有用的语义类(例如天空、建筑物、树木、道路、人行道、车辆、人物等)的每个像素返回一个标签。除了像素标签之外,Scene Semantics API 还提供每个像素标签的置信度值,并提供一种在户外场景中查询给定标签的普遍性的易用方法。

从左到右依次为输入图像示例、像素标签的语义图像以及相应的置信度图像:

输入图像、语义图像和语义置信度图像的示例。

前提条件

确保您了解基本 AR 概念以及如何配置 ARCore 会话,然后再继续。

启用场景语义

新的 ARCore 会话中,检查用户的设备是否支持 Scene Semantics API。由于处理能力限制,并非所有兼容 ARCore 的设备都支持 Scene Semantics API。

为节省资源,ARCore 上默认停用 Scene Semantics。启用语义模式,让您的应用使用 Scene Semantics API。

// Check whether the user's device supports the Scene Semantics API.
int32_t is_scene_semantics_supported = 0;
ArSession_isSemanticModeSupported(ar_session, AR_SEMANTIC_MODE_ENABLED, &is_scene_semantics_supported);

// Configure the session for AR_SEMANTIC_MODEL_ENABLED.
ArConfig* ar_config = NULL;
ArConfig_create(ar_session, &ar_config);
if (is_scene_semantics_supported) {
  ArConfig_setSemanticMode(ar_session, ar_config, AR_SEMANTIC_MODE_ENABLED);
}
CHECK(ArSession_configure(ar_session, ar_config) == AR_SUCCESS);
ArConfig_destroy(ar_config);

获取语义图像

启用 Scene Semantics 后,就可以检索语义图像了。语义图像是 AR_IMAGE_FORMAT_Y8 图像,其中每个像素都对应一个由 ArSemanticLabel 定义的语义标签。

使用 ArFrame_acquireSemanticImage() 获取语义图像:

// Retrieve the semantic image for the current frame, if available.
ArImage* semantic_image = NULL;
if (ArFrame_acquireSemanticImage(ar_session, ar_frame, &semantic_image) != AR_SUCCESS) {
  // No semantic image retrieved for this frame.
  // The output image may be missing for the first couple frames before the model has had a chance to run yet.
  return;
}
// If a semantic image is available, use it here.

输出语义图像应在会话开始大约 1-3 帧后可用,具体取决于设备。

获取置信度图像

除了为每个像素提供标签的语义图像之外,该 API 还提供了相应像素置信度值的置信度图像。置信度图像是一张 AR_IMAGE_FORMAT_Y8 图像,其中每个像素对应于 [0, 255] 范围内的一个值,对应于与每个像素的语义标签关联的概率。

使用 ArFrame_acquireSemanticConfidenceImage() 获取语义置信度图像:

// Retrieve the semantic confidence image for the current frame, if available.
ArImage* semantic_confidence_image = NULL;
if (ArFrame_acquireSemanticConfidenceImage(ar_session, ar_frame, &semantic_confidence_image) != AR_SUCCESS) {
  // No semantic confidence image retrieved for this frame.
  // The output image may be missing for the first couple frames before the model has had a chance to run yet.
  return;
}
// If a semantic confidence image is available, use it here.

输出置信度图像应在会话开始大约 1-3 帧后显示,具体取决于设备。

查询语义标签的像素比例

您还可以查询当前帧中属于特定类别(例如星空)的像素比例。与返回语义图像和对特定标签执行像素级搜索相比,此查询的效率更高。返回的分数是 [0.0, 1.0] 范围内的浮点值。

使用 ArFrame_getSemanticLabelFraction() 获取给定标签的分数:

// Retrieve the fraction of pixels for the semantic label sky in the current frame.
float out_fraction = 0.0f;
if (ArFrame_getSemanticLabelFraction(ar_session, ar_frame, AR_SEMANTIC_LABEL_SKY, &out_fraction) != AR_SUCCESS) {
  // No fraction of semantic labels was retrieved for this frame.
}