注意
混合现实 Academy 教程在设计时考虑了第一代) (HoloLens 和混合现实沉浸式头戴显示设备。 因此,我们认为对于仍在为这些设备寻求开发指导的开发人员保留这些教程非常重要。 这些教程将不会使用用于 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 月) 撰写 (时经过测试和验证的内容。 您可以自由使用最新软件,如 安装工具 一文中所列,但不应假设本课程中的信息与您在比下面列出的更新软件中找到的信息完全匹配。
建议使用以下硬件和软件参加本课程:
- 与 Windows Mixed Reality 兼容的开发电脑,用于沉浸式 (VR) 耳机开发
- 启用了开发人员模式的 Windows 10 Fall Creators Update (或更高版本)
- 最新的 Windows 10 SDK
- Unity 2017.4
- Visual Studio 2017
- Windows Mixed Reality沉浸式 (VR) 头戴显示设备或启用了开发者模式的 Microsoft HoloLens
- 连接到电脑 (的用于沉浸式耳机开发) 的相机
- 用于 Azure 设置和自定义视觉 API 检索的 Internet 访问
- 针对希望 自定义视觉 服务识别的每个对象,至少包含 5 个 (5 个) 图像 (10 (10 个) 建议) 的系列。 如果您愿意,您可以使用 本课程中已提供的图像 (计算机鼠标和键盘) 。
准备工作
- 为避免在生成此项目时遇到问题,强烈建议在根文件夹或近根文件夹中创建本教程中提到的项目, (长文件夹路径可能会导致生成时) 出现问题。
- 设置并测试 HoloLens。 如果需要有关设置 HoloLens 的帮助, 请务必参阅 HoloLens 设置一文。
- 开始开发新的 HoloLens 应用时,最好执行校准和传感器优化, (有时为每个用户) 执行这些任务会有所帮助。
有关校准的帮助,请按照此 链接访问 HoloLens 校准文章。
有关传感器优化的帮助,请按照此 链接访问 HoloLens 传感器优化文章。
第 1 章 - 自定义视觉服务门户
若要在 Azure 中使用自定义视觉服务,需要配置服务实例,以供应用程序使用。
首先,导航到自定义视觉服务主页。
单击“ 开始” 按钮。
登录到自定义视觉服务门户。
注意
如果您还没有 Azure 帐户,则需要创建一个。 如果你在课堂或实验室情况下按照本教程学习,请向教师或监考人员寻求有关设置新帐户的帮助。
首次登录后,系统将提示您使用 “服务条款” 面板。 单击复选框同意条款。 然后单击“ 我同意”。
同意条款后,您将被导航到门户的 项目 部分。 单击 “新建项目”。
右侧将出现一个选项卡,提示您为项目指定一些字段。
插入项目 的名称 。
插入项目的 说明 (可选) 。
选择 资源组 或新建资源组。 资源组提供了一种监视、控制访问、预配和管理 Azure 资产集合计费的方法。 建议将与单个项目 (关联的所有 Azure 服务保留在公共资源组) 下,例如这些课程) 。
将 “项目类型 ”设置为 “分类”
将 域 设置为 “常规”。
若要详细了解 Azure 资源组,请访问资源组文章。
完成后,单击“创建项目”,将重定向到自定义视觉服务项目页面。
第 2 章 - 训练自定义视觉项目
进入自定义视觉门户后,您的主要目标是训练您的项目以识别图像中的特定对象。 对于希望应用程序识别的每个对象,至少需要 5 个 (5 个) 图像,但最好是 10 个 (10 个) 。 您可以使用本课程提供的图像 (计算机鼠标和键盘) 。
训练自定义视觉服务项目:
点击标记旁边的 + 按钮 。
添加要识别的对象 的名称 。 单击“ 保存”。
您会注意到您的 标记 已添加 (您可能需要重新加载页面才能使其显示在) 。 如果尚未选中新标记旁边的复选框,请单击该复选框。
单击页面中央的 “添加图像” 。
点击浏览 本地文件,搜索,然后选择您要上传的图像,最少为 5 (5) 。 请记住,所有这些图像都应包含您正在训练的对象。
注意
可以一次选择多张图像进行上传。
在选项卡中看到图像后,在“ 我的标记 ”框中选择相应的标签。
单击“ 上传文件”。 将开始上传文件。 确认上传后,单击 “完成”。
重复相同的过程以创建一个名为 Keyboard 的新标签并为其上传适当的照片。 创建新标签后,请确保 取消选中鼠标 ,以显示“ 添加图像 ”窗口。
设置好两个标签后,点击训练 ,第一个训练迭代将开始构建。
生成后,你将能够看到两个按钮,分别是“ 设为默认值 ”和 “预测 URL”。 单击“首先 设为默认值 ”,然后单击 “预测 URL”。
注意
由此提供的终结点 URL 设置为已标记为默认值的任何 迭代 。 因此,如果稍后进行新 迭代 并将其更新为默认值,则无需更改代码。
单击预测 URL 后,打开 记事本,复制并粘贴 URL 和 预测密钥,以便在稍后代码中需要时可以检索它。
单击屏幕右上角的 齿轮 。
复制 训练密钥 并将其粘贴到 记事本中,以供以后使用。
同时复制 项目 ID,并将其粘贴到 记事本 文件中,以供以后使用。
第 3 章 - 设置 Unity 项目
以下是使用混合现实进行开发的典型设置,因此是适用于其他项目的良好模板。
打开 Unity 并单击“新建”。
您现在需要提供一个 Unity 项目名称。 插入 AzureCustomVision。 确保项目模板设置为 3D。 将 “位置 ”设置为适合你的位置 (记住,离根目录越近越好) 。 然后,单击 创建项目。
打开 Unity 后,有必要检查默认脚本编辑器是否设置为 Visual Studio。 转到“ 编辑>首选项 ”,然后从新窗口导航到 “外部工具”。 将 外部脚本编辑器 更改为 Visual Studio 2017。 关闭“ 首选项 ”窗口。
接下来,转到“文件>生成设置”并选择“通用 Windows 平台”,然后单击“切换平台”按钮应用所选内容。
在 仍在“文件 > 生成设置” 中时,请确保:
目标设备 设置为 HoloLens
对于沉浸式头戴显示设备,请将 “目标设备 ”设置为 “任何设备”。
生成类型设置为D3D
SDK 设置为 最新安装
Visual Studio 版本 设置为 最新安装
“生成并运行”设置为“本地计算机”
保存场景并将其添加到生成中。
通过选择 “添加打开的场景”执行此操作。 将显示一个保存窗口。
为此场景以及以后的任何场景创建一个新文件夹,然后选择 新建文件夹(New folder ) 按钮,创建一个新文件夹,将其命名为 场景(Scenes)。
打开新创建的 Scenes 文件夹,然后在 File name: 文本字段中键入 CustomVisionScene,然后单击 Save 。
请注意,您必须将 Unity 场景保存在 Assets 文件夹中,因为它们必须与 Unity 项目相关联。 创建场景文件夹 (和其他类似文件夹) 是构建Unity项目的典型方法。
生成 设置中的其余设置暂时应保留为默认值。
在 “生成设置 ”窗口中,单击“ 播放器设置 ”按钮,这将在 检查器 所在的空间中打开相关面板。
在此面板中,需要验证一些设置:
在 “其他设置 ”选项卡中:
脚本运行时版本 应为 实验性 (.NET 4.6 等效) ,这将触发重启编辑器的需要。
脚本后端 应为 .NET
API 兼容级别 应为 .NET 4.6
在“发布设置”选项卡的“功能”下,检查:
InternetClient
网络摄像头
麦克风
在面板的下方,在“发布设置”) 下面的“XR 设置” (中找到,勾选“支持虚拟现实”,确保已添加 Windows Mixed Reality SDK。
返回到“生成设置”Unity C# 项目不再灰显;勾选旁边的复选框。
关闭“生成设置”窗口。
将场景和项目保存 (文件 保存 > 场景 / 文件 > 保存项目) 。
第 4 章 - 在 Unity 中导入 Newtonsoft DLL
重要
如果希望跳过本课程的 Unity 设置组件,直接继续学习代码,请随时下载此 Azure-MR-302b.unitypackage,将其作为自定义包导入到项目中,然后从第 6 章继续。
本课程需要使用 Newtonsoft 库,你可以将其作为 DLL 添加到资产中。 可以从此链接下载包含此库的软件包。 要将 Newtonsoft 库导入到您的项目中,请使用本课程附带的 Unity 包。
使用“资产>导入包>自定义包”菜单选项将 .unitypackage 添加到 Unity。
在弹出的“导入Unity包”框中,确保已选择“ ((包括) 插件)下的所有内容。
单击“ 导入 ”按钮以将项目添加到项目。
转到项目视图中“插件”下的 Newtonsoft 文件夹,然后选择 Newtonsoft.Json 插件。
选择 Newtonsoft.Json 插件后,确保取消选中“任何平台”,然后确保也取消选中WSAPlayer,然后单击“应用”。 这只是为了确认文件配置是否正确。
注意
标记这些插件会将它们配置为仅在 Unity 编辑器中使用。 WSA 文件夹中有一组不同的文件,将在从 Unity 导出项目后使用。
接下来,您需要打开 Newtonsoft 文件夹中的 WSA 文件夹。 你将看到刚刚配置的同一文件的副本。 选择文件,然后在检查器中确保
- 取消选中任何平台
- 仅选中WSAPlayer
- 选中“不处理”进程
第 5 章 - 相机设置
在 层次结构(Hierarchy) 面板中,选择 主摄像机(Main Camera)。
选择后,您将能够在检查器面板中看到主摄像机的所有组件。
相机对象必须命名为 Main Camera, (注意拼写!)
主相机 标记 必须设置为 MainCamera , (注意拼写!)
确保 “变换位置 ”设置为 0, 0, 0
将 “清除标志 ”设置为 “纯色 ” (忽略此项以进行沉浸式头戴显示设备) 。
将相机组件的 背景 色设置为 黑色,alpha 0 (十六进制代码:#00000000) 对于沉浸式头戴显示设备) , (忽略此选项。
第 6 章 - 创建 CustomVisionAnalyser 类。
此时已准备好编写一些代码。
您将从 CustomVisionAnalyser 类开始。
注意
下面所示的代码中对自定义视觉服务的调用是使用自定义视觉 REST API 进行的。 通过使用它,您将了解如何实现和使用此 API, (了解如何在您自己的) 上实现类似的内容很有用。 请注意,Microsoft 提供了自定义视觉服务 SDK,该 SDK 也可用于调用服务。 有关详细信息,请参阅自定义视觉服务 SDK 一文。
此类负责:
加载捕获为字节数组的最新图像。
将字节数组发送到 Azure 自定义视觉服务实例进行分析。
以 JSON 字符串形式接收响应。
反序列化响应并将生成的 预测 传递给 SceneOrganiser 类,该类将负责响应的显示方式。
要创建此类,请执行以下操作:
右键单击位于 项目(Project Panel) 中的 资产文件夹(Asset Folder) ,然后单击 创建文件夹(Create > Folder) 。 调用文件夹 Scripts。
双击刚刚创建的文件夹将其打开。
右键单击文件夹,然后单击“ 创建>C# 脚本”。 将脚本命名为 CustomVisionAnalyser。
双击新的 CustomVisionAnalyser 脚本以使用 Visual Studio 将其打开。
更新文件顶部的命名空间以匹配以下内容:
using System.Collections; using System.IO; using UnityEngine; using UnityEngine.Networking; using Newtonsoft.Json;在 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 变量。 您在课程前面已将这些内容复制到 记事本 。
现在需要添加 Awake () 代码来初始化 Instance 变量:
/// <summary> /// Initialises this class /// </summary> private void Awake() { // Allows this instance to behave like a singleton Instance = this; }删除方法 启动 () 和 更新 () 。
接下来,在其下方添加带有静态 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); }在返回 Unity 之前,请务必在 Visual Studio 中保存更改。
第 7 章 - 创建 CustomVisionObjects 类
您现在要创建的类是 CustomVisionObjects 类。
此脚本包含许多对象,其他类使用这些对象序列化和反序列化对自定义视觉服务进行的调用。
警告
请务必注意自定义视觉服务提供的终结点,因为以下 JSON 结构已设置为使用自定义视觉预测 v2.0。 如果有不同的版本,则可能需要更新以下结构。
要创建此类,请执行以下操作:
右键单击“ 脚本 ”文件夹,然后单击“ 创建>C# 脚本”。 调用脚本 CustomVisionObjects。
双击新的 CustomVisionObjects 脚本以使用 Visual Studio 将其打开。
将以下命名空间添加到文件顶部:
using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking;删除 CustomVisionObjects 类中的 Start () 和 Update () 方法;此类现在应为空。
在 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 类
此类将识别来自用户的语音输入。
要创建此类,请执行以下操作:
右键单击“ 脚本 ”文件夹,然后单击“ 创建>C# 脚本”。 调用脚本 VoiceRecognizer。
双击新的 VoiceRecognizer 脚本以使用 Visual Studio 将其打开。
在 VoiceRecognizer 类上方添加以下命名空间:
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Windows.Speech;然后在 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>();添加 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; }删除 Update () 方法。
添加以下处理程序,每当识别到语音输入时调用此处理程序:
/// <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(); } }在返回 Unity 之前,请务必在 Visual Studio 中保存更改。
注意
不要担心可能出现错误的代码,因为您很快就会提供更多类,这将修复这些问题。
第 9 章 - 创建 CustomVisionTrainer 类
此类将链接一系列 Web 调用以训练自定义视觉服务。 每个调用都将在代码正上方进行详细解释。
要创建此类,请执行以下操作:
右键单击“ 脚本 ”文件夹,然后单击“ 创建>C# 脚本”。 调用脚本 CustomVisionTrainer。
双击新的 CustomVisionTrainer 脚本以使用 Visual Studio 将其打开。
在 CustomVisionTrainer 类上方添加以下命名空间:
using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using UnityEngine; using UnityEngine.Networking;然后在 CustomVisionTrainer 类中的 Start () 方法上方添加以下变量。
注意
此处使用的训练 URL 在自定义视觉训练 1.2 文档中提供,其结构为:https://southcentralus.api.cognitive.microsoft.com/customvision/v1.2/Training/projects/{projectId}/
有关详细信息,请访问自定义视觉训练 v1.2 参考 API。警告
请务必注意 自定义视觉 服务为训练模式提供的终结点,因为在 CustomVisionObjects 类) 中 (使用的 JSON 结构已设置为与 自定义视觉 训练 v1.2 配合使用。 如果有不同的版本,则可能需要更新 对象 结构。
/// <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;重要
确保添加之前记下的 服务密钥 (培训密钥) 值和项目 ID 值;这些值是在课程 (第 2 章第 10 步开始 的课程中从门户收集的值) 。
添加以下 Start () 和 Awake () 方法。 这些方法在初始化时调用,并包含用于设置 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); }删除 Update () 方法。 此类将不需要它。
添加 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(); }添加 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)); } }添加 SubmitImageForTraining () 方法。 此方法将开始自定义视觉服务训练过程。 第一步是从服务检索与用户经过验证的语音输入相关联的 标记 ID 。 然后, 标记 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()); }添加 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)); } } }添加 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)); } } }添加 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(); } }要添加到此类中的最后一个方法是 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); }在返回 Unity 之前,请务必在 Visual Studio 中保存更改。
第 10 章 - 创建 SceneOrganizerer 类
此类将:
创建一个 Cursor 对象以附加到主相机。
创建一个 Label 对象,该对象将在服务识别真实世界的对象时显示。
通过将适当的组件连接到主摄像头来设置主摄像头。
在分析模式下,在运行时在相对于主摄像机位置的适当世界空间中生成标签,并显示从自定义视觉服务接收的数据。
在 训练模式下,生成将显示训练过程不同阶段的 UI。
要创建此类,请执行以下操作:
右键单击“ 脚本 ”文件夹,然后单击“ 创建>C# 脚本”。 将脚本命名为 SceneOrganizerer。
双击新的 SceneOrganiser 脚本以使用 Visual Studio 将其打开。
只需一个命名空间,从 SceneOrganiser 类上方删除其他命名空间:
using UnityEngine;然后在 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;删除 “启动 () ”和“ 更新” () 方法。
在变量的正下方添加 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"); }现在添加 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; }添加 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>"; } }添加 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")}"); } } } }最后,添加 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; }在返回 Unity 之前,请务必在 Visual Studio 中保存更改。
重要
在继续之前,请打开 CustomVisionAnalyser 类,并在 AnalyseLastImageCaptured () 方法中取消 注释 以下行:
AnalysisObject analysisObject = new AnalysisObject();
analysisObject = JsonConvert.DeserializeObject<AnalysisObject>(jsonResponse);
SceneOrganiser.Instance.SetTagsToLastLabel(analysisObject);
第 11 章 - 创建 ImageCapture 类
您要创建的下一个类是 ImageCapture 类。
此类负责:
使用 HoloLens 相机捕获图像并将其存储到 应用 文件夹中。
处理来自用户的点击手势。
维护用于确定应用程序是在分析模式下还是在训练模式下运行的枚举值。
要创建此类,请执行以下操作:
转到之前创建的 Scripts 文件夹。
右键单击文件夹,然后单击 “创建 > C# 脚本”。 将脚本命名为 ImageCapture。
双击新的 ImageCapture 脚本以使用 Visual Studio 将其打开。
将文件顶部的命名空间替换为以下内容:
using System; using System.IO; using System.Linq; using UnityEngine; using UnityEngine.XR.WSA.Input; using UnityEngine.XR.WSA.WebCam;然后在 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;现在需要添加用于 Awake () 和 Start () 方法的代码:
/// <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"); }实现在出现 Tap 手势时将调用的处理程序。
/// <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 方法充当启动或停止照片捕获循环的开关。
在 训练 模式下,它将从相机捕获图像。
当光标为绿色时,表示相机可用于拍摄图像。
当光标为红色时,表示相机正忙。
添加应用程序用于启动图像捕获过程并存储图像的方法。
/// <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); }); }); }添加在捕获照片和准备好进行分析时将调用的处理程序。 然后,结果将传递给 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(); }在返回 Unity 之前,请务必在 Visual Studio 中保存更改。
现在所有脚本都已完成,返回 Unity 编辑器,然后单击 SceneOrganiser 类,从 Scripts 文件夹拖动到层次结构面板中的主摄像机对象。
第 12 章 - 生成前
若要对应用程序执行全面测试,需要将其旁加载到 HoloLens 上。
在执行此操作之前,请确保:
第 2 章中提到的所有设置都已正确设置。
主摄像机、检查器面板中的所有字段都已正确分配。
脚本 SceneOrganiser 附加到 主相机 对象。
确保将 预测键 插入 predictionKey 变量。
您已将 预测终结点 插入 predictionEndpoint 变量。
已将训练密钥插入 CustomVisionTrainer 类的 trainingKey 变量中。
已将项目 ID 插入 CustomVisionTrainer 类的 projectId 变量中。
第 13 章 - 生成和旁加载应用程序
要开始 生成 过程,请执行以下操作:
转到 “文件 > 生成设置”。
勾选 Unity C# 项目。
单击 “生成”。 Unity 将启动一个文件资源管理器窗口,您需要在其中创建并选择一个文件夹以在其中构建应用程序。 现在创建该文件夹,并将其命名为 App。 然后选择 应用程序 文件夹后,单击选择 文件夹。
Unity 会开始将项目生成到 App 文件夹。
Unity 完成生成后 (可能需要一些时间) ,它将在任务栏 (检查 生成的位置打开一个文件资源管理器窗口,因为它可能并不总是显示在窗口上方,但会通知你添加了新窗口) 。
若要部署到 HoloLens,请执行以下操作:
你将需要用于远程部署) 的 HoloLens (的 IP 地址,并确保 HoloLens 处于 开发者模式。 为此:
戴上 HoloLens 时,打开 “设置”。
转到 网络 & Internet>Wi-Fi>高级选项
请注意 IPv4 地址。
接下来,导航回“设置”,然后导航到“面向开发人员的更新 & 安全性>”
将 开发人员模式设置为开启。
(App 文件夹) 导航到新的 Unity 版本,并使用 Visual Studio 打开解决方案文件。
在 解决方案配置 中,选择 “调试”。
在解决方案平台中,选择 x86 远程计算机。 系统将提示你在 HoloLens (插入远程设备的 IP 地址 ,在本例中是你) 记下的。
转到 “生成” 菜单,然后单击“ 部署解决方案 ”,将应用程序旁加载到 HoloLens。
应用现在应该显示在 HoloLens 上的已安装应用列表中,可供启动!
注意
要部署到沉浸式头戴显示设备,请将 “解决方案平台 ”设置为 “本地计算机”,并将 “配置 ”设置为 “调试”,并以 x86 作为 平台。 然后使用 “生成 ”菜单项,选择“ 部署解决方案”部署到本地计算机。
若要使用本应用程序
若要在训练模式和预测模式之间切换应用功能,需要更新位于 ImageCapture 类中的 Awake () 方法中的 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 章 - 评估和改进自定义视觉模型
为了使您的服务更加准确,您需要继续训练用于预测的模型。 这是通过使用您的新应用程序来实现的,包括 训练 模式和 预测 模式,后者要求您访问门户,这就是本章中介绍的内容。 准备好多次重新访问您的门户,以不断改进您的模型。
再次前往 Azure 自定义视觉 门户,进入项目后,从页面顶部中心 (选择“预测”选项卡) :
您将看到应用程序运行时发送到服务的所有图像。 如果将鼠标悬停在图像上,它们将为您提供针对该图像所做的预测:
选择其中一个图像将其打开。 打开后,您将在右侧看到对该图像所做的预测。 如果您的预测是正确的,并且您希望将此图像添加到服务的训练模型中,请单击 “我的标记” 输入框,然后选择要关联的标记。 完成后,单击右下角的 “保存并关闭” 按钮,然后继续查看下一张图像。
返回图像网格后,您会注意到已添加标签到 (并保存) 的图像将被删除。 如果您发现任何您认为其中没有标记项的图像,则可以通过单击该图像上的勾号来删除它们 (可以对多个图像执行此操作) 然后单击网格页面右上角的 删除 。 在随后的弹出窗口中,您可以单击 是, 删除 或 否,分别确认删除或取消删除。
准备好继续时,单击右上角的绿色“ 训练” 按钮。 您的服务模型将使用您现在提供的所有图像进行训练 (这将使其更准确) 。 训练完成后,请确保再次单击“ 设为默认值 ”按钮,以便预测 URL 继续使用服务的最新迭代。
完成的自定义视觉 API 应用程序
恭喜,你构建了一个混合现实应用,该应用利用 Azure 自定义视觉 API 来识别真实世界的对象、训练服务模型,并显示对所看到内容的置信度。
奖励练习
练习 1
训练自定义视觉服务以识别更多对象。
练习 2
作为扩展所学内容的一种方式,请完成以下练习:
识别物体时播放声音。
练习 3
使用 API 使用应用正在分析的相同图像重新训练服务,以便使服务更加准确, () 同时进行预测和训练。