瞭解如何在自己的應用程式中使用 Scene Semantics API。
Scene Semantics API 提供以機器學習模型為基礎的即時語意資訊,可讓開發人員瞭解使用者周遭的場景。假設有室外場景的圖片,API 會傳回一系列實用語意類別 (如天空、建築物、樹、道路、人行道、車輛、人物等) 中的每個像素標籤。除了像素標籤之外,Sene Semantics API 也提供每個像素標籤的可信度值,而且可讓您輕鬆查詢在戶外場景中特定標籤的盛行情況。
從左到右查看輸入圖片範例、像素標籤的語意圖片,以及對應的可信度圖片:
必要條件
請務必先瞭解基本 AR 概念,以及如何設定 ARCore 工作階段,然後再繼續操作。
啟用場景語意
在新的 ARCore 工作階段中,檢查使用者的裝置是否支援 Scene Semantics API。由於處理功率限制,並非所有與 ARCore 相容的裝置都支援 Scene Semantics API。
為節省資源,ARCore 會預設停用場景語意。啟用語意模式,讓應用程式使用 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);
取得語意圖片
啟用場景語意後,即可擷取語意圖片。語意圖片是 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. }