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

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

Scene Semantics API 提供以機器學習模型為基礎的即時語意資訊,可讓開發人員瞭解使用者周遭的場景。假設有室外場景的圖片,API 會傳回一系列實用語意類別 (如天空、建築物、樹、道路、人行道、車輛、人物等) 中的每個像素標籤。除了像素標籤之外,Sene Semantics 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];
}