了解 iOS 上的用户环境

了解如何在您自己的应用中使用 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。

GARSessionConfiguration *configuration = [[GARSessionConfiguration alloc] init];
if ([self.garSession isSemanticModeSupported:GARSemanticModeEnabled]) {
    configuration.semanticMode = GARSemanticModeEnabled;
}

NSError *error;
[self.garSession setConfiguration:configuration error:&error];

获取语义图像

启用 Scene Semantics 之后,即可检索语义图像。该语义图像是一幅 kCVPixelFormatType_OneComponent8 图像,其中每个像素对应一个由 GARSemanticLabel 定义的语义标签。

使用 GARFrame.semanticImage 获取语义图像:

CVPixelBuffer semanticImage = garFrame.semanticImage;
if (semanticImage) {
    // Use the semantic image here
} else {
    // Semantic images are not available.
    // The output image may be missing for the first couple frames before the model has had a
    // chance to run yet.
}

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

获取置信度图片

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

使用 GARFrame.semanticConfidenceImage 获取语义置信度图像:

CVPixelBuffer confidenceImage = garFrame.semanticConfidenceImage;
if (confidenceImage) {
    // Use the semantic image here
} else {
    // Semantic images are not available.
    // The output image may be missing for the first couple frames before the model has had a
    // chance to run yet.
}

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

查询语义标签的像素比例

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

使用 fractionForSemanticLabel: 获取给定标签的比例:

// Ensure that semantic data is present for the GARFrame.
if (garFrame.semanticImage) {
    float fraction = [garFrame fractionForSemanticLabel:GARSemanticLabelSky];
}