瞭解 iOS 上的使用者環境's 環境

瞭解如何在自家應用程式中使用 Scene Semantics API

透過場景語意 API,開發人員可以提供機器學習模型的即時語意資訊,瞭解使用者周遭的場景。當您提供戶外場景的圖片時,API 會針對每個像素傳回一組實用的語意類別標籤,例如天空、建築物、樹木、道路、人行道、車輛、人物等。除了像素標籤之外,場景語意 API 還會為每個像素標籤提供信心值,並提供簡單易用的查詢方式,可查詢特定標籤在戶外場景中的盛行率。

從左至右,分別為輸入圖片、像素標籤的語意圖片,以及對應的信心圖片:

輸入圖片、語意圖片和語意信心圖片的範例。

必要條件

請務必先瞭解基本 AR 概念,並瞭解如何設定 ARCore 工作階段,再繼續操作。

啟用場景語意

新的 ARCore 工作階段中,確認使用者的裝置是否支援 Scene Semantics API。由於處理效能受限,並非所有 ARCore 相容裝置都支援 Scene Semantics API。

為了節省資源,ARCore 預設會停用場景語意。啟用語意模式,讓應用程式使用 Scene Semantics API。

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

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

取得語意圖像

啟用場景語意後,即可擷取語意圖像。語意圖片是 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];
}