HoloLens (第 1 代) 和 Azure 302b:自訂視覺


注意事項

Mixed Reality Academy 教學課程是專為第 1 代) (HoloLens 和 Mixed Reality 沉浸式頭戴式裝置而設計。 因此,我們認為為仍在尋找這些裝置開發指引的開發人員保留這些教學課程非常重要。 這些教學課程將不會以適用於 HoloLens 2 的最新工具集或互動進行更新。 系統將會維持其繼續在支援的裝置上運作。 未來將會發佈一系列新的教學課程,示範如何針對 HoloLens 2 進行開發。 張貼這些教學課程時,將會更新此通知以連結。


在本課程中,您將學習如何使用混合實境應用程式中的Azure 自訂視覺功能來辨識所提供影像中的自訂視覺內容。

該服務將允許您使用對象圖像訓練機器學習模型。 接著,您將使用經過訓練的模型來辨識類似的物件,如 Microsoft HoloLens 的相機擷取畫面或連接到電腦的相機所提供的,以取得沉浸式 (VR) 頭戴式裝置。

課程成果

Azure 自訂視覺 是 Microsoft 認知服務,可讓開發人員建置自訂影像分類器。 然後,這些分類器可以與新圖像一起使用,以識別或分類該新圖像中的物件。 該服務提供了一個簡單、易於使用的在線門戶,以簡化流程。 如需詳細資訊,請造訪 Azure 自訂視覺 服務頁面。

完成本課程後,您將擁有一個能夠在兩種模式下工作的混合現實應用程序:

  • 分析模式:透過上傳影像、建立標籤,以及訓練服務手動設定 自訂視覺 服務,以辨識不同的物件, (在此案例中為滑鼠和鍵盤) 。 接著,您將建立 HoloLens 應用程式,該應用程式將使用相機擷取影像,並嘗試辨識真實世界中的這些物件。

  • 訓練模式:您將實作可在應用程式中啟用「訓練模式」的程式碼。 訓練模式可讓您使用 HoloLens 的相機擷取影像、將擷取的影像上傳至服務,以及訓練自訂視覺模型。

本課程將教您如何將結果從自訂視覺服務取得到以 Unity 為基礎的範例應用程式。 將這些概念套用至您可能正在建置的自訂應用程式將由您決定。

裝置支援

課程 HoloLens 沉浸式頭戴裝置
MR 和 Azure 302b:自訂視覺 ✔️ ✔️

注意事項

雖然本課程主要著重於 HoloLens,但您也可以將本課程中學到的知識套用到Windows Mixed Reality沉浸式 (VR) 頭戴式裝置。 由於沉浸式 (VR) 頭戴式裝置沒有可存取的相機,因此您需要將外部相機連接到您的電腦。 跟隨課程時,您會看到為支援沉浸式 (VR) 頭戴式裝置而可能需要進行的任何變更的附註。

先決條件

注意事項

本教學課程專為具有 Unity 和 C# 基本經驗的開發人員所設計。 另請注意,本文件中的先決條件和書面說明僅代表撰寫本文時已經測試和驗證的內容 (2018 年 7 月) 。 您可以自由使用最新的軟體,如 安裝工具 一文中所列,但不應假設本課程中的資訊與下面列出的較新軟體中的資訊完全相符。

我們針對本課程建議使用下列硬體和軟體:

開始之前

  1. 若要避免在建置此專案時發生問題,強烈建議您在根或近根資料夾中建立本教學課程中提及的專案, (長資料夾路徑可能會在建置時) 造成問題。
  2. 設定並測試您的 HoloLens。 如果您需要設定 HoloLens 的支援, 請務必瀏覽 HoloLens 設定文章。
  3. 開始開發新的 HoloLens 應用程式時,最好執行校正和感應器調整, (有時可協助每個使用者) 執行這些工作。

如需校正方面的說明,請遵循此 連結前往 HoloLens 校正文章。

如需感應器微調的說明,請遵循此 連結至 HoloLens 感應器微調文章。

第 1 章 - 自訂視覺服務入口網站

若要在 Azure 中使用自訂視覺服務,您必須設定服務執行個體,以供應用程式使用。

  1. 首先,導覽至自訂視覺服務主頁面。

  2. 按一下 [開始使用 ] 按鈕。

    開始使用自訂視覺服務

  3. 登入自訂視覺服務入口網站。

    登入至入口網站

    注意事項

    如果您還沒有 Azure 帳戶,則需要建立一個帳戶。 如果您是在教室或實驗室的情況下遵循本教學課程,請請向您的講師或監考人員尋求設定新帳戶的協助。

  4. 首次登入後,系統將提示您使用 [服務條款 ] 面板。 點擊核取方塊以同意條款。 然後點擊我 同意。

    服務條款

  5. 同意這些條款後,您將被導航到門戶的 項目 部分。 按一下 [新增專案]。

    建立新專案

  6. 右側會出現一個選項卡,提示您為專案指定一些欄位。

    1. 插入專案 的名稱 。

    2. 插入專案的 描述 (選擇性) 。

    3. 選擇 資源群組 或建立新資源群組。 資源群組提供一種方式來監視、控制存取、佈建和管理 Azure 資產集合的計費。 建議將所有 Azure 服務與單一專案相關聯 (例如,這些課程) 在一個公共資源群組) 下。

    4. 將 專案類型 設定為 分類

    5. 將 網域 設定為 [一般]。

      設定網域

      如果您想要深入瞭解 Azure 資源群組,請瀏覽資源群組文章。

  7. 完成後,按一下「建立專案」,您將被重新導向至自訂視覺服務專案頁面。

第 2 章 - 訓練您的自訂視覺專案

進入自訂視覺入口網站後,您的主要目標是訓練您的專案來識別影像中的特定物件。 對於您想要應用程式辨識的每個物件,您至少需要 5 (5) 影像,不過最好是 10 (10) 的 10 個影像。 您可以使用本課程提供的影像 (電腦滑鼠和鍵盤) 。

若要訓練您的自訂視覺服務專案:

  1. 按一下 +[標籤] 旁的按鈕。

    新增標籤

  2. 新增您要辨識的物件 名稱 。 按一下 [儲存]。

    新增物件名稱並儲存

  3. 您會注意到您的 標籤 已新增, (您可能需要重新載入頁面才能顯示) 。 如果尚未核取新標籤旁邊的核取方塊,請按一下。

    啟用新標籤

  4. 按一下頁面中央的 [ 新增影像 ]。

    新增影像

  5. 按一下 [ 瀏覽本機檔案],然後搜尋並選取您要上傳的影像,至少為 5 (5) 。 請記住,所有這些圖像都應該包含您正在訓練的對象。

    注意事項

    您可以一次選取多個影像進行上傳。

  6. 在索引標籤中看到影像後,請在 [ 我的標籤 ] 方塊中選取適當的標籤。

    選取標籤

  7. 按一下 [ 上傳檔案]。 檔案將開始上傳。 確認上傳後,按一下 完成。

    上傳檔案

  8. 重複相同的程序,建立名為 [鍵盤] 的新標記,並為其上傳適當的相片。 建立新標籤之後,請務必取消選取滑鼠,以顯示 [新增影像] 視窗。

  9. 設定好兩個標籤後,按一下 [訓練],第一個訓練反覆運算將開始建置。

    啟用訓練反覆運算

  10. 建置完成後,您將可以看到兩個名為 [ 設為預設 ] 和 [預測 URL] 的按鈕。 先按一下 [設為預設 值],然後按一下 [預測 URL]。

    製作預設和預測 URL

    注意事項

    由此提供的端點 URL 會設定為標示為預設值的任何 反覆運算 。 因此,如果您稍後製作新的 反覆運算 並將其更新為預設值,則不需要變更程式碼。

  11. 按一下預測 URL 後,請開啟 記事本,複製並貼上 URL 和 預測金鑰,以便稍後在代碼中需要時擷取它。

    複製並貼上 URL 和預測索引鍵

  12. 按一下畫面右上方的 齒輪 。

    按一下齒輪圖示以開啟設定

  13. 複製訓練 金鑰 並將其貼到 記事本中以供以後使用。

    複製訓練金鑰

  14. 同時複製您的 專案識別碼,並將其貼到 記事本 檔案中以供日後使用。

    複製專案識別碼

第 3 章 - 設定 Unity 專案

以下是使用混合實境進行開發的一般設定,因此是其他專案的良好範本。

  1. 開啟 Unity 並按一下 [新增]。

    建立新的 Unity 專案

  2. 您現在需要提供 Unity 專案名稱。 插入 AzureCustomVision。 確定專案範本已設定為 3D。 將 [位置] 設定在適合您的位置, (請記住,靠近根目錄越好) 。 然後,按一下「 建立專案」。

    設定專案設定

  3. 開啟 Unity 後,值得檢查預設 的指令碼編輯器 是否設定為 Visual Studio。 移至 [ 編輯>喜好設定 ],然後從新視窗瀏覽至 [外部工具]。 將 外部指令碼編輯器 變更為 Visual Studio 2017。 關閉 [喜好設定 ] 視窗。

    設定外部工具

  4. 接下來,轉到文件>構建設置並選擇通用 Windows 平台,然後單擊切換平台按鈕以應用您的選擇。

    設定組建設定

  5. 同時,請繼續在 [ 檔案 > 組建設定] 中,並確認:

    1. 目標裝置設定 為 HoloLens

      對於沉浸式頭戴裝置,請將 [目標裝置] 設定為 [任何裝置]。

    2. [組建類型 ] 設定為 [D3D]

    3. SDK 設定為 最新安裝

    4. Visual Studio 版本 設定為 最新安裝

    5. [建置並執行] 設定為 [本機電腦]

    6. 儲存場景並將它新增至組建。

      1. 請選取 [新增開啟場景] 來執行此動作。 將會顯示一個儲存視窗。

        將開啟的場景新增至組建清單

      2. 為此和任何未來的場景建立新資料夾,然後選取 [新增資料夾] 按鈕,以建立一個新資料夾,將其命名為 [場景]。

        建立新場景資料夾

      3. 開啟新建立的 [場景] 資料夾,然後在 [檔案名稱: ] 文字欄位中,輸入 CustomVisionScene,然後按一下 [ 儲存]。

        命名新場景檔案

        請注意,您必須將 Unity 場景保存在 Assets 資料夾中,因為它們必須與 Unity 專案相關聯。 ) 建立場景資料夾 (和其他類似資料夾是建構 Unity 專案的典型方式。

    7. [ 組建設定] 中的其餘設定目前應保留為預設值。

      預設組建設定

  6. 在 “構建設置 ”窗口中,單擊 “播放器設置 ”按鈕,這將在 檢查器 所在空間中打開相關面板。

  7. 在此面板中,需要驗證一些設定:

    1. 在 [ 其他設定 ] 索引標籤中:

      1. 指令碼執行階段版本 應為實驗 性 (.NET 4.6 等效) ,這會觸發重新啟動編輯器的需求。

      2. 指令碼後端 應該是 .NET

      3. API 相容性層級 應為 .NET 4.6

      設定 API 相容性

    2. 在 [發佈設定 ] 索引標籤的 [功能] 底下,檢查:

      1. InternetClient

      2. 網路攝影機

      3. 麥克風

      設定發佈設定

    3. 在面板下方的 XR 設定 (下方的 [發佈設定]) ,勾選 [支援虛擬實境],確定已新增 Windows Mixed Reality SDK。

    設定 XR 設定

  8. 返回組 建設定Unity C# 專案 不再呈現灰色;勾選此旁邊的核取方塊。

  9. 關閉 [組建設定] 視窗。

  10. 將您的場景和專案儲存 (檔案 > 儲存場景/檔案 > 儲存專案) 。

第 4 章 - 在 Unity 中匯入 Newtonsoft DLL

重要事項

如果您想要略過本課程的 Unity 設定元件,直接繼續進入程式碼,請隨時下載此 Azure-MR-302b.unitypackage,將其作為自訂套件導入到您的專案中,然後從第 6 章繼續。

本課程需要使用 Newtonsoft 程式庫,您可以將其作為 DLL 新增至您的資產。 包含 此程式庫的套件可從此連結下載。 若要將 Newtonsoft 程式庫匯入專案中,請使用本課程隨附的 Unity 套件。

  1. 使用 [資產>匯入套件>自訂套件] 功能表選項,將 .unitypackage 新增至 Unity。

  2. 在彈出的 [匯入 Unity 套件] 方塊中,確定已選取 [ (] 下的所有項目,並包含 [) 外掛程式]。

    匯入所有套件項目

  3. 按一下 [匯入] 按鈕,將項目新增至您的專案。

  4. 移至專案檢視中 [外掛程式] 下的 Newtonsoft 資料夾,然後選取 Newtonsoft.Json 外掛程式。

    選取 Newtonsoft 外掛程式

  5. 選取 Newtonsoft.Json 外掛程式後,請確保未選取 [任何平台],然後確定也未選取WSAPlayer,然後按一下 [套用]。 這只是為了確認檔案配置正確。

    設定 Newtonsoft 外掛程式

    注意事項

    標記這些外掛程式會將它們設定為僅在 Unity 編輯器中使用。 從 Unity 匯出專案後,將使用 WSA 資料夾中有一組不同的它們。

  6. 接下來,您需要開啟 Newtonsoft 資料夾中的 WSA 資料夾。 您會看到剛才設定之相同檔案的複本。 選取檔案,然後在檢查器中,確保

    • 未選取任何平台
    • 僅勾選WSAPlayer
    • 已勾選[不要處理] 程序

    設定 Newtonsoft 外掛程式平台設定

第 5 章 - 相機設定

  1. 在「階層」面板中,選取 「主相機」。

  2. 選擇後,您將能夠在檢查器面板中看到主相機的所有組件。

    1. 相機物件必須命名為 [主相機], (注意拼字!)

    2. [主相機 ] 標記 必須設定為 [主相機 ], (注意拼字!)

    3. 確定 [轉換位置] 已設定為 0、0、0

    4. 將 [清除標幟] 設定為 [純色 ] (忽略此選項,以進行沉浸式耳機) 。

    5. 將相機元件的 背景 色彩設定為黑色 ,Alpha 0 (十六進位代碼:#00000000) (忽略此選項以進行沉浸式耳機) 。

    設定相機元件屬性

第 6 章 - 建立 CustomVisionAnalyser 類別。

此時,您已準備好撰寫一些程式碼。

您將從 CustomVisionAnalyser 類別開始。

注意事項

以下程式碼中對自訂視覺服務的呼叫是使用自訂視覺 REST API 進行的。 透過使用它,您將了解如何實作和使用此 API, (有助於了解如何在您自己的) 上實作類似的內容。 請注意,Microsoft 提供自訂視覺服務 SDK,也可用來呼叫服務。 如需詳細資訊,請造訪自訂視覺服務 SDK 一文。

本班級負責:

  • 載入以位元組陣列擷取的最新影像。

  • 將位元組陣列傳送至 Azure 自訂視覺服務執行個體進行分析。

  • 以 JSON 字串形式接收回應。

  • 還原序列化回應,並將產生的 預測 傳遞給 SceneOrganiser 類別,該類別會處理回應的顯示方式。

若要建立此類別:

  1. 以滑鼠右鍵按一下位於「專案」面板中的「資產資料夾」,然後按一下「建立>資料夾」。 呼叫資料夾 Scripts。

    建立指令碼資料夾

  2. 按兩下剛建立的資料夾,將其開啟。

  3. 以滑鼠右鍵按一下資料夾內,然後按一下 [建立>C# 指令碼]。 將指令碼命名為 CustomVisionAnalyser。

  4. 按兩下新的 CustomVisionAnalyser 指令碼,以使用 Visual Studio 開啟它。

  5. 更新檔案頂端的命名空間,使其符合下列內容:

    using System.Collections;
    using System.IO;
    using UnityEngine;
    using UnityEngine.Networking;
    using Newtonsoft.Json;
    
  6. 在 CustomVisionAnalyser 類別中,新增下列變數:

        /// <summary>
        /// Unique instance of this class
        /// </summary>
        public static CustomVisionAnalyser Instance;
    
        /// <summary>
        /// Insert your Prediction Key here
        /// </summary>
        private string predictionKey = "- Insert your key here -";
    
        /// <summary>
        /// Insert your prediction endpoint here
        /// </summary>
        private string predictionEndpoint = "Insert your prediction endpoint here";
    
        /// <summary>
        /// Byte array of the image to submit for analysis
        /// </summary>
        [HideInInspector] public byte[] imageBytes;
    

    注意事項

    請務必將 預測金鑰 插入 predictionKey 變數,並將 預測端點 插入 predictionEndpoint 變數。 您在課程稍早已將這些內容複製到 [記事本 ]。

  7. 現在需要新增喚 醒 () 的程式碼來初始化實例變數:

        /// <summary>
        /// Initialises this class
        /// </summary>
        private void Awake()
        {
            // Allows this instance to behave like a singleton
            Instance = this;
        }
    
  8. 刪除 Start () 和 Update () 方法。

  9. 接下來,將協程 (與靜態 GetImageAsByteArray () 方法加) ,這將獲得 ImageCapture 類別捕獲的圖像的分析結果。

    注意事項

    在 AnalyseImageCapture 協程中,有一個呼叫您尚未建立的 SceneOrganiser 類別。 因此,請暫時保留這些台詞。

        /// <summary>
        /// Call the Computer Vision Service to submit the image.
        /// </summary>
        public IEnumerator AnalyseLastImageCaptured(string imagePath)
        {
            WWWForm webForm = new WWWForm();
            using (UnityWebRequest unityWebRequest = UnityWebRequest.Post(predictionEndpoint, webForm))
            {
                // Gets a byte array out of the saved image
                imageBytes = GetImageAsByteArray(imagePath);
    
                unityWebRequest.SetRequestHeader("Content-Type", "application/octet-stream");
                unityWebRequest.SetRequestHeader("Prediction-Key", predictionKey);
    
                // The upload handler will help uploading the byte array with the request
                unityWebRequest.uploadHandler = new UploadHandlerRaw(imageBytes);
                unityWebRequest.uploadHandler.contentType = "application/octet-stream";
    
                // The download handler will help receiving the analysis from Azure
                unityWebRequest.downloadHandler = new DownloadHandlerBuffer();
    
                // Send the request
                yield return unityWebRequest.SendWebRequest();
    
                string jsonResponse = unityWebRequest.downloadHandler.text;
    
                // The response will be in JSON format, therefore it needs to be deserialized    
    
                // The following lines refers to a class that you will build in later Chapters
                // Wait until then to uncomment these lines
    
                //AnalysisObject analysisObject = new AnalysisObject();
                //analysisObject = JsonConvert.DeserializeObject<AnalysisObject>(jsonResponse);
                //SceneOrganiser.Instance.SetTagsToLastLabel(analysisObject);
            }
        }
    
        /// <summary>
        /// Returns the contents of the specified image file as a byte array.
        /// </summary>
        static byte[] GetImageAsByteArray(string imageFilePath)
        {
            FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
    
            BinaryReader binaryReader = new BinaryReader(fileStream);
    
            return binaryReader.ReadBytes((int)fileStream.Length);
        }
    
  10. 請務必先在 Visual Studio 中儲存變更,再返回 Unity。

第 7 章 - 建立 CustomVisionObjects 類別

您現在要建立的類別是 CustomVisionObjects 類別。

此指令碼包含許多其他類別用來序列化和還原序列化對自訂視覺服務的呼叫的物件。

警告

請務必記下自訂視覺服務提供的端點,因為下列 JSON 結構已設定為與自訂視覺預測 v2.0 搭配使用。 如果您有不同的版本,您可能需要更新下列結構。

若要建立此類別:

  1. 以滑鼠右鍵按一下 [ 指令碼 ] 資料夾內,然後按一下 [ 建立>C# 指令碼]。 呼叫指令碼 CustomVisionObjects。

  2. 按兩下新的 CustomVisionObjects 指令碼,以使用 Visual Studio 開啟它。

  3. 將下列命名空間新增至檔案頂端:

    using System;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.Networking;
    
  4. 刪除 CustomVisionObjects 類別內的 Start () 和 Update () 方法;此類別現在應為空。

  5. 在 CustomVisionObjects 類別之外新增下列類別。 Newtonsoft 程式庫會使用這些物件來序列化和還原序列化回應資料:

    // The objects contained in this script represent the deserialized version
    // of the objects used by this application 
    
    /// <summary>
    /// Web request object for image data
    /// </summary>
    class MultipartObject : IMultipartFormSection
    {
        public string sectionName { get; set; }
    
        public byte[] sectionData { get; set; }
    
        public string fileName { get; set; }
    
        public string contentType { get; set; }
    }
    
    /// <summary>
    /// JSON of all Tags existing within the project
    /// contains the list of Tags
    /// </summary> 
    public class Tags_RootObject
    {
        public List<TagOfProject> Tags { get; set; }
        public int TotalTaggedImages { get; set; }
        public int TotalUntaggedImages { get; set; }
    }
    
    public class TagOfProject
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public int ImageCount { get; set; }
    }
    
    /// <summary>
    /// JSON of Tag to associate to an image
    /// Contains a list of hosting the tags,
    /// since multiple tags can be associated with one image
    /// </summary> 
    public class Tag_RootObject
    {
        public List<Tag> Tags { get; set; }
    }
    
    public class Tag
    {
        public string ImageId { get; set; }
        public string TagId { get; set; }
    }
    
    /// <summary>
    /// JSON of Images submitted
    /// Contains objects that host detailed information about one or more images
    /// </summary> 
    public class ImageRootObject
    {
        public bool IsBatchSuccessful { get; set; }
        public List<SubmittedImage> Images { get; set; }
    }
    
    public class SubmittedImage
    {
        public string SourceUrl { get; set; }
        public string Status { get; set; }
        public ImageObject Image { get; set; }
    }
    
    public class ImageObject
    {
        public string Id { get; set; }
        public DateTime Created { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        public string ImageUri { get; set; }
        public string ThumbnailUri { get; set; }
    }
    
    /// <summary>
    /// JSON of Service Iteration
    /// </summary> 
    public class Iteration
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public bool IsDefault { get; set; }
        public string Status { get; set; }
        public string Created { get; set; }
        public string LastModified { get; set; }
        public string TrainedAt { get; set; }
        public string ProjectId { get; set; }
        public bool Exportable { get; set; }
        public string DomainId { get; set; }
    }
    
    /// <summary>
    /// Predictions received by the Service after submitting an image for analysis
    /// </summary> 
    [Serializable]
    public class AnalysisObject
    {
        public List<Prediction> Predictions { get; set; }
    }
    
    [Serializable]
    public class Prediction
    {
        public string TagName { get; set; }
        public double Probability { get; set; }
    }
    

第 8 章 - 建立 VoiceRecognizer 類別

此類別將辨識使用者輸入的語音。

若要建立此類別:

  1. 以滑鼠右鍵按一下 [ 指令碼 ] 資料夾內,然後按一下 [ 建立>C# 指令碼]。 呼叫指令碼 VoiceRecognizer。

  2. 按兩下新的 VoiceRecognizer 指令碼,以使用 Visual Studio 開啟它。

  3. 在 VoiceRecognizer 類別上方新增下列命名空間:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using UnityEngine;
    using UnityEngine.Windows.Speech;
    
  4. 然後,在 VoiceRecognizer 類別內,在 Start () 方法的上方,新增下列變數:

        /// <summary>
        /// Allows this class to behave like a singleton
        /// </summary>
        public static VoiceRecognizer Instance;
    
        /// <summary>
        /// Recognizer class for voice recognition
        /// </summary>
        internal KeywordRecognizer keywordRecognizer;
    
        /// <summary>
        /// List of Keywords registered
        /// </summary>
        private Dictionary<string, Action> _keywords = new Dictionary<string, Action>();
    
  5. 新增 Awake () 和 Start () 方法,後者會設定在將標籤與影像相關聯時要辨識的使用者 關鍵字 :

        /// <summary>
        /// Called on initialization
        /// </summary>
        private void Awake()
        {
            Instance = this;
        }
    
        /// <summary>
        /// Runs at initialization right after Awake method
        /// </summary>
        void Start ()
        {
    
            Array tagsArray = Enum.GetValues(typeof(CustomVisionTrainer.Tags));
    
            foreach (object tagWord in tagsArray)
            {
                _keywords.Add(tagWord.ToString(), () =>
                {
                    // When a word is recognized, the following line will be called
                    CustomVisionTrainer.Instance.VerifyTag(tagWord.ToString());
                });
            }
    
            _keywords.Add("Discard", () =>
            {
                // When a word is recognized, the following line will be called
                // The user does not want to submit the image
                // therefore ignore and discard the process
                ImageCapture.Instance.ResetImageCapture();
                keywordRecognizer.Stop();
            });
    
            //Create the keyword recognizer 
            keywordRecognizer = new KeywordRecognizer(_keywords.Keys.ToArray());
    
            // Register for the OnPhraseRecognized event 
            keywordRecognizer.OnPhraseRecognized += KeywordRecognizer_OnPhraseRecognized;
        }
    
  6. 刪除 Update () 方法。

  7. 新增下列處理常式,每當辨識語音輸入時就會呼叫該處理常式:

        /// <summary>
        /// Handler called when a word is recognized
        /// </summary>
        private void KeywordRecognizer_OnPhraseRecognized(PhraseRecognizedEventArgs args)
        {
            Action keywordAction;
            // if the keyword recognized is in our dictionary, call that Action.
            if (_keywords.TryGetValue(args.text, out keywordAction))
            {
                keywordAction.Invoke();
            }
        }
    
  8. 請務必先在 Visual Studio 中儲存變更,再返回 Unity。

注意事項

不要擔心可能出現錯誤的代碼,因為您很快就會提供更多類別,這將修復這些問題。

第 9 章 - 建立 CustomVisionTrainer 類別

此類別會鏈結一系列 Web 呼叫,以訓練自訂視覺服務。 每個呼叫都會在代碼正上方進行詳細解釋。

若要建立此類別:

  1. 以滑鼠右鍵按一下 [ 指令碼 ] 資料夾內,然後按一下 [ 建立>C# 指令碼]。 呼叫指令碼 CustomVisionTrainer。

  2. 按兩下新的 CustomVisionTrainer 指令碼,以使用 Visual Studio 將其開啟。

  3. 在 CustomVisionTrainer 類別上方新增下列命名空間:

    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    using UnityEngine;
    using UnityEngine.Networking;
    
  4. 然後在 CustomVisionTrainer 類別內,在 Start () 方法上方新增下列變數。

    注意事項

    此處使用的訓練URL是在自訂視覺訓練1.2檔案中提供的,且具有下列結構:https://southcentralus.api.cognitive.microsoft.com/customvision/v1.2/Training/projects/{projectId}/
    如需詳細資訊,請瀏覽自訂視覺訓練 v1.2 參考 API。

    警告

    請務必記下 自訂視覺 服務針對訓練模式提供的端點,因為 CustomVisionObjects 類別) 內 (使用的 JSON 結構已設定為搭配 自訂視覺 訓練 v1.2 使用。 如果您有不同的版本,您可能需要更新 Objects 結構。

        /// <summary>
        /// Allows this class to behave like a singleton
        /// </summary>
        public static CustomVisionTrainer Instance;
    
        /// <summary>
        /// Custom Vision Service URL root
        /// </summary>
        private string url = "https://southcentralus.api.cognitive.microsoft.com/customvision/v1.2/Training/projects/";
    
        /// <summary>
        /// Insert your prediction key here
        /// </summary>
        private string trainingKey = "- Insert your key here -";
    
        /// <summary>
        /// Insert your Project Id here
        /// </summary>
        private string projectId = "- Insert your Project Id here -";
    
        /// <summary>
        /// Byte array of the image to submit for analysis
        /// </summary>
        internal byte[] imageBytes;
    
        /// <summary>
        /// The Tags accepted
        /// </summary>
        internal enum Tags {Mouse, Keyboard}
    
        /// <summary>
        /// The UI displaying the training Chapters
        /// </summary>
        private TextMesh trainingUI_TextMesh;
    

    重要事項

    請務必新增之前記下的服務 金鑰 (訓練金鑰) 值和 專案識別碼 值;這些是您在課程 (第 2 章步驟 10 開始的課程中從入口網站收集 的值) 。

  5. 新增下列 [開始 () ] 和 [喚醒] () 方法。 這些方法會在初始化時呼叫,並包含設定 UI 的呼叫:

        /// <summary>
        /// Called on initialization
        /// </summary>
        private void Awake()
        {
            Instance = this;
        }
    
        /// <summary>
        /// Runs at initialization right after Awake method
        /// </summary>
        private void Start()
        { 
            trainingUI_TextMesh = SceneOrganiser.Instance.CreateTrainingUI("TrainingUI", 0.04f, 0, 4, false);
        }
    
  6. 刪除 Update () 方法。 此班級將不需要它。

  7. 新增 RequestTagSelection () 方法。 當已擷取影像並儲存在裝置中,且現在已準備好提交至自訂視覺服務以訓練影像時,第一個呼叫此方法。 這個方法會在訓練 UI 中顯示一組關鍵字,使用者可以用來標記已擷取的影像。 它也會提醒 VoiceRecognizer 類別開始聆聽使用者的語音輸入。

        internal void RequestTagSelection()
        {
            trainingUI_TextMesh.gameObject.SetActive(true);
            trainingUI_TextMesh.text = $" \nUse voice command \nto choose between the following tags: \nMouse\nKeyboard \nor say Discard";
    
            VoiceRecognizer.Instance.keywordRecognizer.Start();
        }
    
  8. 新增 VerifyTag () 方法。 這個方法會接收 VoiceRecognizer 類別所辨識的語音輸入,並驗證其有效性,然後開始訓練程序。

        /// <summary>
        /// Verify voice input against stored tags.
        /// If positive, it will begin the Service training process.
        /// </summary>
        internal void VerifyTag(string spokenTag)
        {
            if (spokenTag == Tags.Mouse.ToString() || spokenTag == Tags.Keyboard.ToString())
            {
                trainingUI_TextMesh.text = $"Tag chosen: {spokenTag}";
                VoiceRecognizer.Instance.keywordRecognizer.Stop();
                StartCoroutine(SubmitImageForTraining(ImageCapture.Instance.filePath, spokenTag));
            }
        }
    
  9. 新增 SubmitImageForTraining () 方法。 此方法會開始自訂視覺服務訓練程序。 第一個步驟是從服務擷取標籤 識別碼 ,該識別碼與使用者經過驗證的語音輸入相關聯。 然後, 標籤 ID 將與影像一起上傳。

        /// <summary>
        /// Call the Custom Vision Service to submit the image.
        /// </summary>
        public IEnumerator SubmitImageForTraining(string imagePath, string tag)
        {
            yield return new WaitForSeconds(2);
            trainingUI_TextMesh.text = $"Submitting Image \nwith tag: {tag} \nto Custom Vision Service";
            string imageId = string.Empty;
            string tagId = string.Empty;
    
            // Retrieving the Tag Id relative to the voice input
            string getTagIdEndpoint = string.Format("{0}{1}/tags", url, projectId);
            using (UnityWebRequest www = UnityWebRequest.Get(getTagIdEndpoint))
            {
                www.SetRequestHeader("Training-Key", trainingKey);
                www.downloadHandler = new DownloadHandlerBuffer();
                yield return www.SendWebRequest();
                string jsonResponse = www.downloadHandler.text;
    
                Tags_RootObject tagRootObject = JsonConvert.DeserializeObject<Tags_RootObject>(jsonResponse);
    
                foreach (TagOfProject tOP in tagRootObject.Tags)
                {
                    if (tOP.Name == tag)
                    {
                        tagId = tOP.Id;
                    }             
                }
            }
    
            // Creating the image object to send for training
            List<IMultipartFormSection> multipartList = new List<IMultipartFormSection>();
            MultipartObject multipartObject = new MultipartObject();
            multipartObject.contentType = "application/octet-stream";
            multipartObject.fileName = "";
            multipartObject.sectionData = GetImageAsByteArray(imagePath);
            multipartList.Add(multipartObject);
    
            string createImageFromDataEndpoint = string.Format("{0}{1}/images?tagIds={2}", url, projectId, tagId);
    
            using (UnityWebRequest www = UnityWebRequest.Post(createImageFromDataEndpoint, multipartList))
            {
                // Gets a byte array out of the saved image
                imageBytes = GetImageAsByteArray(imagePath);           
    
                //unityWebRequest.SetRequestHeader("Content-Type", "application/octet-stream");
                www.SetRequestHeader("Training-Key", trainingKey);
    
                // The upload handler will help uploading the byte array with the request
                www.uploadHandler = new UploadHandlerRaw(imageBytes);
    
                // The download handler will help receiving the analysis from Azure
                www.downloadHandler = new DownloadHandlerBuffer();
    
                // Send the request
                yield return www.SendWebRequest();
    
                string jsonResponse = www.downloadHandler.text;
    
                ImageRootObject m = JsonConvert.DeserializeObject<ImageRootObject>(jsonResponse);
                imageId = m.Images[0].Image.Id;
            }
            trainingUI_TextMesh.text = "Image uploaded";
            StartCoroutine(TrainCustomVisionProject());
        }
    
  10. 新增 TrainCustomVisionProject () 方法。 提交並標記影像之後,就會呼叫這個方法。 它會建立新的反覆運算,使用所有先前提交至服務的影像,加上剛上傳的影像進行訓練。 訓練完成後,此方法會呼叫方法,將新建立的 反覆 運算設定為 預設值,讓您用於分析的端點就是最新訓練的反覆運算。

        /// <summary>
        /// Call the Custom Vision Service to train the Service.
        /// It will generate a new Iteration in the Service
        /// </summary>
        public IEnumerator TrainCustomVisionProject()
        {
            yield return new WaitForSeconds(2);
    
            trainingUI_TextMesh.text = "Training Custom Vision Service";
    
            WWWForm webForm = new WWWForm();
    
            string trainProjectEndpoint = string.Format("{0}{1}/train", url, projectId);
    
            using (UnityWebRequest www = UnityWebRequest.Post(trainProjectEndpoint, webForm))
            {
                www.SetRequestHeader("Training-Key", trainingKey);
                www.downloadHandler = new DownloadHandlerBuffer();
                yield return www.SendWebRequest();
                string jsonResponse = www.downloadHandler.text;
                Debug.Log($"Training - JSON Response: {jsonResponse}");
    
                // A new iteration that has just been created and trained
                Iteration iteration = new Iteration();
                iteration = JsonConvert.DeserializeObject<Iteration>(jsonResponse);
    
                if (www.isDone)
                {
                    trainingUI_TextMesh.text = "Custom Vision Trained";
    
                    // Since the Service has a limited number of iterations available,
                    // we need to set the last trained iteration as default
                    // and delete all the iterations you dont need anymore
                    StartCoroutine(SetDefaultIteration(iteration)); 
                }
            }
        }
    
  11. 新增 SetDefaultIteration () 方法。 這個方法會將先前建立並訓練的反覆運算設定為 預設值。 完成之後,此方法必須刪除服務中現有的先前反覆運算。 在撰寫本課程時,服務中最多允許同時存在 10 (10 次) 反覆運算。

        /// <summary>
        /// Set the newly created iteration as Default
        /// </summary>
        private IEnumerator SetDefaultIteration(Iteration iteration)
        {
            yield return new WaitForSeconds(5);
            trainingUI_TextMesh.text = "Setting default iteration";
    
            // Set the last trained iteration to default
            iteration.IsDefault = true;
    
            // Convert the iteration object as JSON
            string iterationAsJson = JsonConvert.SerializeObject(iteration);
            byte[] bytes = Encoding.UTF8.GetBytes(iterationAsJson);
    
            string setDefaultIterationEndpoint = string.Format("{0}{1}/iterations/{2}", 
                                                            url, projectId, iteration.Id);
    
            using (UnityWebRequest www = UnityWebRequest.Put(setDefaultIterationEndpoint, bytes))
            {
                www.method = "PATCH";
                www.SetRequestHeader("Training-Key", trainingKey);
                www.SetRequestHeader("Content-Type", "application/json");
                www.downloadHandler = new DownloadHandlerBuffer();
    
                yield return www.SendWebRequest();
    
                string jsonResponse = www.downloadHandler.text;
    
                if (www.isDone)
                {
                    trainingUI_TextMesh.text = "Default iteration is set \nDeleting Unused Iteration";
                    StartCoroutine(DeletePreviousIteration(iteration));
                }
            }
        }
    
  12. 新增 DeletePreviousIteration () 方法。 這個方法會尋找並刪除先前的非預設反覆運算:

        /// <summary>
        /// Delete the previous non-default iteration.
        /// </summary>
        public IEnumerator DeletePreviousIteration(Iteration iteration)
        {
            yield return new WaitForSeconds(5);
    
            trainingUI_TextMesh.text = "Deleting Unused \nIteration";
    
            string iterationToDeleteId = string.Empty;
    
            string findAllIterationsEndpoint = string.Format("{0}{1}/iterations", url, projectId);
    
            using (UnityWebRequest www = UnityWebRequest.Get(findAllIterationsEndpoint))
            {
                www.SetRequestHeader("Training-Key", trainingKey);
                www.downloadHandler = new DownloadHandlerBuffer();
                yield return www.SendWebRequest();
    
                string jsonResponse = www.downloadHandler.text;
    
                // The iteration that has just been trained
                List<Iteration> iterationsList = new List<Iteration>();
                iterationsList = JsonConvert.DeserializeObject<List<Iteration>>(jsonResponse);
    
                foreach (Iteration i in iterationsList)
                {
                    if (i.IsDefault != true)
                    {
                        Debug.Log($"Cleaning - Deleting iteration: {i.Name}, {i.Id}");
                        iterationToDeleteId = i.Id;
                        break;
                    }
                }
            }
    
            string deleteEndpoint = string.Format("{0}{1}/iterations/{2}", url, projectId, iterationToDeleteId);
    
            using (UnityWebRequest www2 = UnityWebRequest.Delete(deleteEndpoint))
            {
                www2.SetRequestHeader("Training-Key", trainingKey);
                www2.downloadHandler = new DownloadHandlerBuffer();
                yield return www2.SendWebRequest();
                string jsonResponse = www2.downloadHandler.text;
    
                trainingUI_TextMesh.text = "Iteration Deleted";
                yield return new WaitForSeconds(2);
                trainingUI_TextMesh.text = "Ready for next \ncapture";
    
                yield return new WaitForSeconds(2);
                trainingUI_TextMesh.text = "";
                ImageCapture.Instance.ResetImageCapture();
            }
        }
    
  13. 要在本類別中新增的最後一個方法是 GetImageAsByteArray () 方法,用於 Web 呼叫,將擷取的影像轉換成位元組陣列。

        /// <summary>
        /// Returns the contents of the specified image file as a byte array.
        /// </summary>
        static byte[] GetImageAsByteArray(string imageFilePath)
        {
            FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
            BinaryReader binaryReader = new BinaryReader(fileStream);
            return binaryReader.ReadBytes((int)fileStream.Length);
        }
    
  14. 請務必先在 Visual Studio 中儲存變更,再返回 Unity。

第 10 章 - 建立 SceneOrganiser 類別

本課程將:

  • 建立「 游標」 物件以貼附至「主相機」。

  • 建立當服務辨識真實世界物件時會出現的 標籤 物件。

  • 透過將適當的組件連接到主相機來設定主相機。

  • 在分析模式下,在運行時,在相對於主相機位置的適當世界空間中生成標籤,並顯示從自訂視覺服務接收的資料。

  • 在 訓練模式中,產生將顯示訓練過程不同階段的 UI。

若要建立此類別:

  1. 以滑鼠右鍵按一下 [ 指令碼 ] 資料夾內,然後按一下 [ 建立>C# 指令碼]。 將指令碼命名為 SceneOrganiser。

  2. 按兩下新的 SceneOrganiser 指令碼,以使用 Visual Studio 開啟它。

  3. 您只需要一個命名空間,從 SceneOrganiser 類別上方移除其他命名空間:

    using UnityEngine;
    
  4. 然後在 SceneOrganiser 類別內,在 Start () 方法上方新增下列變數:

        /// <summary>
        /// Allows this class to behave like a singleton
        /// </summary>
        public static SceneOrganiser Instance;
    
        /// <summary>
        /// The cursor object attached to the camera
        /// </summary>
        internal GameObject cursor;
    
        /// <summary>
        /// The label used to display the analysis on the objects in the real world
        /// </summary>
        internal GameObject label;
    
        /// <summary>
        /// Object providing the current status of the camera.
        /// </summary>
        internal TextMesh cameraStatusIndicator;
    
        /// <summary>
        /// Reference to the last label positioned
        /// </summary>
        internal Transform lastLabelPlaced;
    
        /// <summary>
        /// Reference to the last label positioned
        /// </summary>
        internal TextMesh lastLabelPlacedText;
    
        /// <summary>
        /// Current threshold accepted for displaying the label
        /// Reduce this value to display the recognition more often
        /// </summary>
        internal float probabilityThreshold = 0.5f;
    
  5. 刪除 Start () 和 Update () 方法。

  6. 在變數的正下方,新增 Awake () 方法,該方法將初始化類別並設定場景。

        /// <summary>
        /// Called on initialization
        /// </summary>
        private void Awake()
        {
            // Use this class instance as singleton
            Instance = this;
    
            // Add the ImageCapture class to this GameObject
            gameObject.AddComponent<ImageCapture>();
    
            // Add the CustomVisionAnalyser class to this GameObject
            gameObject.AddComponent<CustomVisionAnalyser>();
    
            // Add the CustomVisionTrainer class to this GameObject
            gameObject.AddComponent<CustomVisionTrainer>();
    
            // Add the VoiceRecogniser class to this GameObject
            gameObject.AddComponent<VoiceRecognizer>();
    
            // Add the CustomVisionObjects class to this GameObject
            gameObject.AddComponent<CustomVisionObjects>();
    
            // Create the camera Cursor
            cursor = CreateCameraCursor();
    
            // Load the label prefab as reference
            label = CreateLabel();
    
            // Create the camera status indicator label, and place it above where predictions
            // and training UI will appear.
            cameraStatusIndicator = CreateTrainingUI("Status Indicator", 0.02f, 0.2f, 3, true);
    
            // Set camera status indicator to loading.
            SetCameraStatus("Loading");
        }
    
  7. 現在新增 CreateCameraCursor () 方法,以建立和定位主要相機游標,以及 CreateLabel () 方法,以建立 分析標籤 物件。

        /// <summary>
        /// Spawns cursor for the Main Camera
        /// </summary>
        private GameObject CreateCameraCursor()
        {
            // Create a sphere as new cursor
            GameObject newCursor = GameObject.CreatePrimitive(PrimitiveType.Sphere);
    
            // Attach it to the camera
            newCursor.transform.parent = gameObject.transform;
    
            // Resize the new cursor
            newCursor.transform.localScale = new Vector3(0.02f, 0.02f, 0.02f);
    
            // Move it to the correct position
            newCursor.transform.localPosition = new Vector3(0, 0, 4);
    
            // Set the cursor color to red
            newCursor.GetComponent<Renderer>().material = new Material(Shader.Find("Diffuse"));
            newCursor.GetComponent<Renderer>().material.color = Color.green;
    
            return newCursor;
        }
    
        /// <summary>
        /// Create the analysis label object
        /// </summary>
        private GameObject CreateLabel()
        {
            // Create a sphere as new cursor
            GameObject newLabel = new GameObject();
    
            // Resize the new cursor
            newLabel.transform.localScale = new Vector3(0.01f, 0.01f, 0.01f);
    
            // Creating the text of the label
            TextMesh t = newLabel.AddComponent<TextMesh>();
            t.anchor = TextAnchor.MiddleCenter;
            t.alignment = TextAlignment.Center;
            t.fontSize = 50;
            t.text = "";
    
            return newLabel;
        }
    
  8. 新增 SetCameraStatus () 方法,其會處理文字網格所用的訊息,以提供相機的狀態。

        /// <summary>
        /// Set the camera status to a provided string. Will be coloured if it matches a keyword.
        /// </summary>
        /// <param name="statusText">Input string</param>
        public void SetCameraStatus(string statusText)
        {
            if (string.IsNullOrEmpty(statusText) == false)
            {
                string message = "white";
    
                switch (statusText.ToLower())
                {
                    case "loading":
                        message = "yellow";
                        break;
    
                    case "ready":
                        message = "green";
                        break;
    
                    case "uploading image":
                        message = "red";
                        break;
    
                    case "looping capture":
                        message = "yellow";
                        break;
    
                    case "analysis":
                        message = "red";
                        break;
                }
    
                cameraStatusIndicator.GetComponent<TextMesh>().text = $"Camera Status:\n<color={message}>{statusText}..</color>";
            }
        }
    
  9. 新增 PlaceAnalysisLabel () 和 SetTagsToLastLabel () 方法,這會產生 自訂視覺 服務的資料並顯示到場景中。

        /// <summary>
        /// Instantiate a label in the appropriate location relative to the Main Camera.
        /// </summary>
        public void PlaceAnalysisLabel()
        {
            lastLabelPlaced = Instantiate(label.transform, cursor.transform.position, transform.rotation);
            lastLabelPlacedText = lastLabelPlaced.GetComponent<TextMesh>();
        }
    
        /// <summary>
        /// Set the Tags as Text of the last label created. 
        /// </summary>
        public void SetTagsToLastLabel(AnalysisObject analysisObject)
        {
            lastLabelPlacedText = lastLabelPlaced.GetComponent<TextMesh>();
    
            if (analysisObject.Predictions != null)
            {
                foreach (Prediction p in analysisObject.Predictions)
                {
                    if (p.Probability > 0.02)
                    {
                        lastLabelPlacedText.text += $"Detected: {p.TagName} {p.Probability.ToString("0.00 \n")}";
                        Debug.Log($"Detected: {p.TagName} {p.Probability.ToString("0.00 \n")}");
                    }
                }
            }
        }
    
  10. 最後,新增 CreateTrainingUI () 方法,當應用程式處於訓練模式時,會產生顯示訓練程序多個階段的 UI。 還將利用此方法創建相機狀態物件。

        /// <summary>
        /// Create a 3D Text Mesh in scene, with various parameters.
        /// </summary>
        /// <param name="name">name of object</param>
        /// <param name="scale">scale of object (i.e. 0.04f)</param>
        /// <param name="yPos">height above the cursor (i.e. 0.3f</param>
        /// <param name="zPos">distance from the camera</param>
        /// <param name="setActive">whether the text mesh should be visible when it has been created</param>
        /// <returns>Returns a 3D text mesh within the scene</returns>
        internal TextMesh CreateTrainingUI(string name, float scale, float yPos, float zPos, bool setActive)
        {
            GameObject display = new GameObject(name, typeof(TextMesh));
            display.transform.parent = Camera.main.transform;
            display.transform.localPosition = new Vector3(0, yPos, zPos);
            display.SetActive(setActive);
            display.transform.localScale = new Vector3(scale, scale, scale);
            display.transform.rotation = new Quaternion();
            TextMesh textMesh = display.GetComponent<TextMesh>();
            textMesh.anchor = TextAnchor.MiddleCenter;
            textMesh.alignment = TextAlignment.Center;
            return textMesh;
        }
    
  11. 請務必先在 Visual Studio 中儲存變更,再返回 Unity。

重要事項

繼續之前,請開啟 CustomVisionAnalyser 類別,並在 AnalyseLastImageCaptured () 方法中, 取消註解 下列行:

  AnalysisObject analysisObject = new AnalysisObject();
  analysisObject = JsonConvert.DeserializeObject<AnalysisObject>(jsonResponse);
  SceneOrganiser.Instance.SetTagsToLastLabel(analysisObject);

第 11 章 - 建立 ImageCapture 類別

下一個您要建立的類別是 ImageCapture 類別。

本班級負責:

  • 使用 HoloLens 相機擷取影像,並將影像儲存在 應用程式 資料夾中。

  • 處理 點選使用者的手勢。

  • 維護決定應用程式將在分析模式或訓練模式中執行的 Enum 值。

若要建立此類別:

  1. 移至您先前建立的 [指令碼] 資料夾。

  2. 以滑鼠右鍵按一下資料夾內,然後按一下 [建立 > C# 指令碼]。 將指令碼命名為 ImageCapture。

  3. 按兩下新的 ImageCapture 指令碼,以使用 Visual Studio 開啟它。

  4. 以下列內容取代檔案頂端的命名空間:

    using System;
    using System.IO;
    using System.Linq;
    using UnityEngine;
    using UnityEngine.XR.WSA.Input;
    using UnityEngine.XR.WSA.WebCam;
    
  5. 然後在 ImageCapture 類別內,在 Start () 方法上方新增下列變數:

        /// <summary>
        /// Allows this class to behave like a singleton
        /// </summary>
        public static ImageCapture Instance;
    
        /// <summary>
        /// Keep counts of the taps for image renaming
        /// </summary>
        private int captureCount = 0;
    
        /// <summary>
        /// Photo Capture object
        /// </summary>
        private PhotoCapture photoCaptureObject = null;
    
        /// <summary>
        /// Allows gestures recognition in HoloLens
        /// </summary>
        private GestureRecognizer recognizer;
    
        /// <summary>
        /// Loop timer
        /// </summary>
        private float secondsBetweenCaptures = 10f;
    
        /// <summary>
        /// Application main functionalities switch
        /// </summary>
        internal enum AppModes {Analysis, Training }
    
        /// <summary>
        /// Local variable for current AppMode
        /// </summary>
        internal AppModes AppMode { get; private set; }
    
        /// <summary>
        /// Flagging if the capture loop is running
        /// </summary>
        internal bool captureIsActive;
    
        /// <summary>
        /// File path of current analysed photo
        /// </summary>
        internal string filePath = string.Empty;
    
  6. 現在需要新增喚 醒 () 和 開始 () 方法的程式碼:

        /// <summary>
        /// Called on initialization
        /// </summary>
        private void Awake()
        {
            Instance = this;
    
            // Change this flag to switch between Analysis Mode and Training Mode 
            AppMode = AppModes.Training;
        }
    
        /// <summary>
        /// Runs at initialization right after Awake method
        /// </summary>
        void Start()
        {
            // Clean up the LocalState folder of this application from all photos stored
            DirectoryInfo info = new DirectoryInfo(Application.persistentDataPath);
            var fileInfo = info.GetFiles();
            foreach (var file in fileInfo)
            {
                try
                {
                    file.Delete();
                }
                catch (Exception)
                {
                    Debug.LogFormat("Cannot delete file: ", file.Name);
                }
            } 
    
            // Subscribing to the HoloLens API gesture recognizer to track user gestures
            recognizer = new GestureRecognizer();
            recognizer.SetRecognizableGestures(GestureSettings.Tap);
            recognizer.Tapped += TapHandler;
            recognizer.StartCapturingGestures();
    
            SceneOrganiser.Instance.SetCameraStatus("Ready");
        }
    
  7. 實作處理常式,該處理常式將在發生點選手勢時呼叫。

        /// <summary>
        /// Respond to Tap Input.
        /// </summary>
        private void TapHandler(TappedEventArgs obj)
        {
            switch (AppMode)
            {
                case AppModes.Analysis:
                    if (!captureIsActive)
                    {
                        captureIsActive = true;
    
                        // Set the cursor color to red
                        SceneOrganiser.Instance.cursor.GetComponent<Renderer>().material.color = Color.red;
    
                        // Update camera status to looping capture.
                        SceneOrganiser.Instance.SetCameraStatus("Looping Capture");
    
                        // Begin the capture loop
                        InvokeRepeating("ExecuteImageCaptureAndAnalysis", 0, secondsBetweenCaptures);
                    }
                    else
                    {
                        // The user tapped while the app was analyzing 
                        // therefore stop the analysis process
                        ResetImageCapture();
                    }
                    break;
    
                case AppModes.Training:
                    if (!captureIsActive)
                    {
                        captureIsActive = true;
    
                        // Call the image capture
                        ExecuteImageCaptureAndAnalysis();
    
                        // Set the cursor color to red
                        SceneOrganiser.Instance.cursor.GetComponent<Renderer>().material.color = Color.red;
    
                        // Update camera status to uploading image.
                        SceneOrganiser.Instance.SetCameraStatus("Uploading Image");
                    }              
                    break;
            }     
        }
    

    注意事項

    在 分析 模式中, TapHandler 方法可作為啟動或停止相片擷取迴圈的切換。

    在 訓練 模式下,它將從相機捕獲圖像。

    當游標為綠色時,表示相機可以拍攝影像。

    當游標為紅色時,表示相機正在忙碌。

  8. 新增應用程式用來啟動映像擷取程序及儲存映像的方法。

        /// <summary>
        /// Begin process of Image Capturing and send To Azure Custom Vision Service.
        /// </summary>
        private void ExecuteImageCaptureAndAnalysis()
        {
            // Update camera status to analysis.
            SceneOrganiser.Instance.SetCameraStatus("Analysis");
    
            // Create a label in world space using the SceneOrganiser class 
            // Invisible at this point but correctly positioned where the image was taken
            SceneOrganiser.Instance.PlaceAnalysisLabel();
    
            // Set the camera resolution to be the highest possible
            Resolution cameraResolution = PhotoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();
    
            Texture2D targetTexture = new Texture2D(cameraResolution.width, cameraResolution.height);
    
            // Begin capture process, set the image format
            PhotoCapture.CreateAsync(false, delegate (PhotoCapture captureObject)
            {
                photoCaptureObject = captureObject;
    
                CameraParameters camParameters = new CameraParameters
                {
                    hologramOpacity = 0.0f,
                    cameraResolutionWidth = targetTexture.width,
                    cameraResolutionHeight = targetTexture.height,
                    pixelFormat = CapturePixelFormat.BGRA32
                };
    
                // Capture the image from the camera and save it in the App internal folder
                captureObject.StartPhotoModeAsync(camParameters, delegate (PhotoCapture.PhotoCaptureResult result)
                {
                    string filename = string.Format(@"CapturedImage{0}.jpg", captureCount);
                    filePath = Path.Combine(Application.persistentDataPath, filename);          
                    captureCount++;              
                    photoCaptureObject.TakePhotoAsync(filePath, PhotoCaptureFileOutputFormat.JPG, OnCapturedPhotoToDisk);              
                });
            });   
        }
    
  9. 新增處理常式,當擷取相片時,以及準備好進行分析時,將呼叫這些處理常式。 然後,結果會根據代碼設定的模式傳遞至 CustomVisionAnalyser 或 CustomVisionTrainer 。

        /// <summary>
        /// Register the full execution of the Photo Capture. 
        /// </summary>
        void OnCapturedPhotoToDisk(PhotoCapture.PhotoCaptureResult result)
        {
                // Call StopPhotoMode once the image has successfully captured
                photoCaptureObject.StopPhotoModeAsync(OnStoppedPhotoMode);
        }
    
    
        /// <summary>
        /// The camera photo mode has stopped after the capture.
        /// Begin the Image Analysis process.
        /// </summary>
        void OnStoppedPhotoMode(PhotoCapture.PhotoCaptureResult result)
        {
            Debug.LogFormat("Stopped Photo Mode");
    
            // Dispose from the object in memory and request the image analysis 
            photoCaptureObject.Dispose();
            photoCaptureObject = null;
    
            switch (AppMode)
            {
                case AppModes.Analysis:
                    // Call the image analysis
                    StartCoroutine(CustomVisionAnalyser.Instance.AnalyseLastImageCaptured(filePath));
                    break;
    
                case AppModes.Training:
                    // Call training using captured image
                    CustomVisionTrainer.Instance.RequestTagSelection();
                    break;
            }
        }
    
        /// <summary>
        /// Stops all capture pending actions
        /// </summary>
        internal void ResetImageCapture()
        {
            captureIsActive = false;
    
            // Set the cursor color to green
            SceneOrganiser.Instance.cursor.GetComponent<Renderer>().material.color = Color.green;
    
            // Update camera status to ready.
            SceneOrganiser.Instance.SetCameraStatus("Ready");
    
            // Stop the capture loop if active
            CancelInvoke();
        }
    
  10. 請務必先在 Visual Studio 中儲存變更,再返回 Unity。

  11. 現在所有指令碼都已完成,請返回 Unity 編輯器,然後按一下 SceneOrganiser 類別,並將類別從 Scripts 資料夾拖曳至 Hierarchy Panel 中的 Main Camera 物件。

第 12 章 - 建置之前

若要執行應用程式的徹底測試,您必須將它側載到 HoloLens 上。

執行此動作之前,請先確定:

  • 第 2 章 中提到的所有設定都已正確設定。

  • 主相機 [檢查器面板] 中的所有欄位均已正確指派。

  • 指令碼 SceneOrganiser 會附加至 Main Camera 物件。

  • 請務必將 預測金鑰 插入 predictionKey 變數。

  • 您已將 預測端點 插入 predictionEndpoint 變數。

  • 您已將訓練金鑰插入 CustomVisionTrainer 類別的 trainingKey 變數。

  • 您已將專案識別碼插入 CustomVisionTrainer 類別的 projectId 變數。

第 13 章 - 建置和側載您的應用程式

若要開始 建置 程序:

  1. 移至 [ 檔案 > 組建設定]。

  2. 勾選 Unity C# 專案。

  3. 按一下 [組建]。 Unity 將啟動一個檔案總管窗口,您需要在其中建立資料夾,然後選擇要在其中建置應用程式的資料夾。 立即建立該資料夾,並將它命名為 App。 然後選取 App 資料夾後,按一下 選取資料夾。

  4. Unity 會開始將專案建置至 App 資料夾。

  5. Unity 完成建置 (可能需要一些時間) ,它會在組建位置開啟檔案總管視窗 (檢查工作列,因為它可能不一定會顯示在視窗上方,但會通知您新增了一個新視窗) 。

若要在 HoloLens 上部署:

  1. 您需要 HoloLens 的 IP 位址 (進行遠端部署) ,並確保您的 HoloLens 處於 開發人員模式。 若要執行這項作業:

    1. 戴上 HoloLens 時,開啟 [設定]。

    2. 前往 網路 & 網際網路>Wi-Fi>進階選項

    3. 請注意 IPv4 位址。

    4. 接下來,請瀏覽回 [設定],然後瀏覽回 [開發人員的更新 & 安全性>]

    5. 設定 開發人員模式為開啟。

  2. (App 資料夾) 瀏覽至新的 Unity 組建,然後使用 Visual Studio 開啟解決方案檔案。

  3. 在 [解決方案設定] 中,選取 [偵錯]。

  4. 在 解決方案平台中,選取 x86,遠端電腦。 系統會提示您將遠端裝置的 IP 位址 插入 HoloLens (,在此案例中是您) 記下的。

    設定 IP 位址

  5. 移至 [組建] 功能表,然後按一下 [ 部署解決方案] ,將應用程式側載至您的 HoloLens。

  6. 您的應用程式現在應該會出現在 HoloLens 上的已安裝應用程式清單中,準備好啟動了!

注意事項

若要部署到沉浸式頭戴式裝置,請將 [解決方案平台 ] 設定為 [本機電腦],並將 [設定 ] 設定為 [偵錯],並以 x86 做為 平台。 然後部署到本機電腦,使用 [建置 ] 功能表項目,選取 [部署解決方案]。

若要使用應用程式

若要在訓練模式和預測模式之間切換應用程式功能,您需要更新位於 ImageCapture 類別內的喚醒 () 方法中的 AppMode 變數。

        // Change this flag to switch between Analysis mode and Training mode 
        AppMode = AppModes.Training;

或

        // Change this flag to switch between Analysis mode and Training mode 
        AppMode = AppModes.Analysis;

在 訓練模式中 :

  • 查看滑鼠或鍵盤,然後使用 [點選] 手勢。

  • 接下來,系統會顯示要求您提供標籤的文字。

  • 說滑鼠或鍵盤。

在 預測 模式中:

  • 查看物件並使用 [點選] 手勢。

  • 提供偵測到的物件將顯示文字,且此文字 (正常化) 的可能性最高。

第 14 章 - 評估和改善您的自訂視覺模型

若要讓您的服務更準確,您必須繼續訓練用於預測的模型。 這是通過使用您的新應用程序來實現的,具有 訓練 和 預測 模式,後者需要您訪問門戶,這就是本章中介紹的內容。 請準備好多次重新瀏覽您的入口網站,以持續改善您的模型。

  1. 再次前往您的 Azure 自訂視覺 入口網站,進入專案後,從頁面頂端中央 (選取 [預測] 索引標籤) :

    選取預測索引標籤

  2. 您將看到應用程式運行時發送到您的服務的所有圖像。 如果您將游標暫留在影像上,影像會提供針對該影像所做的預測:

    預測影像清單

  3. 選取其中一個影像以開啟它。 打開後,您將在右側看到對該圖像所做的預測。 如果您的預測正確,而且您想要將此影像新增至服務的訓練模型,請按一下 [我的標籤 ] 輸入方塊,然後選取您要關聯的標籤。 完成後,單擊右下角的 “保存並關閉” 按鈕,然後繼續下一張圖像。

    選取要開啟的影像

  4. 回到圖像網格後,您會注意到已向 (添加標籤並保存) 的圖像將被刪除。 如果您發現任何您認為其中沒有標記項目的影像,您可以刪除它們,方法是按一下該影像上的勾號 (可以對多個影像執行此操作,) 然後按一下網格頁面右上角的 刪除 。 在隨後的快顯視窗中,您可以按一下 [是]、[刪除] 或 [否],以確認刪除或取消刪除。

    刪除影像

  5. 當您準備好繼續時,請按一下右上角的綠色 [訓練 ] 按鈕。 您的服務模型將使用您現在提供的所有影像進行訓練 (這將使其更準確) 。 訓練完成後,請務必再次按一下 [ 設為預設 ] 按鈕,讓您的 預測 URL 繼續使用服務的最新反覆運算。

    開始訓練服務模型 選取 [設定預設值] 選項

完成的自訂視覺 API 應用程式

恭喜!您建置混合實境應用程式,該應用程式利用 Azure 自訂視覺 API 來辨識真實世界的物件、訓練服務模型,並顯示對已看到內容的信賴度。

完成的專案範例

獎勵練習

練習 1

訓練您的自訂視覺服務以辨識更多物件。

練習 2

為了擴展您所學到的知識,請完成以下練習:

辨識物件時播放音效。

練習 3

使用 API 使用應用程式正在分析的相同影像重新訓練您的服務,因此為了讓服務更準確, () 同時進行預測和訓練。