HoloLens2端Unity应用调用Azure Face API出现响应反序列化异常
问题描述
我基于Unity 2021.3.4f1开发运行于HoloLens 2的人脸识别应用,编辑器内运行一切正常,但部署到HoloLens设备运行时出现故障。我使用版本为2.8.0.0的Microsoft Azure Cognitive Services Face API,接入方式参考官方人脸检测文档与C# SDK快速入门文档。
核心调用代码片段如下:
private async Task DetectFaceExtractAsync(IFaceClient client, string filepath, string recognitionModel) { Debug.Log("--- DETECT FACE ---"); IList<DetectedFace> detectedFaces; // 指定需要提取的人脸特征 List<FaceAttributeType> features = new List<FaceAttributeType> { FaceAttributeType.Blur, FaceAttributeType.Emotion, FaceAttributeType.Exposure, FaceAttributeType.HeadPose, FaceAttributeType.Noise, FaceAttributeType.Occlusion, FaceAttributeType.Smile, FaceAttributeType.QualityForRecognition }; // 从图片中检测人脸并返回指定属性 try { using (FileStream faceimagestream = File.OpenRead(filepath)) { detectedFaces = await client.Face.DetectWithStreamAsync( faceimagestream, returnFaceAttributes: features, detectionModel: DetectionModel.Detection01, recognitionModel: recognitionModel); } } catch (Exception e) { Debug.Log("Exception: " + e.Message); throw e; } }
接收Azure返回的响应时,程序抛出*"Unable to deserialize the response"*异常。该异常仅在待检测图片中存在可识别人脸时于HoloLens设备端触发,Unity编辑器环境下无法复现;若图片中无人脸,接口响应可正常完成反序列化。
调试输出截图:
问题更新
经测试,即使仅请求2022年6月21日Face API接口限制调整后仍对外开放的人脸属性(模糊度、曝光度、头部姿态、噪声、遮挡、识别质量),异常仍会触发,对应属性请求代码如下:
List<FaceAttributeType> features = new List<FaceAttributeType> { FaceAttributeType.Blur, FaceAttributeType.Exposure, FaceAttributeType.HeadPose, FaceAttributeType.Noise, FaceAttributeType.Occlusion, FaceAttributeType.QualityForRecognition };
解决方案
这是Azure Face SDK 2.8.0稳定版在UWP ARM架构(HoloLens 2运行环境)下的已知兼容bug:SDK默认的枚举序列化配置在IL2CPP编译后,无法正确映射接口返回的人脸属性枚举字符串值;没人脸时接口返回空数组,不会触发属性解析逻辑所以不报错,有人脸时返回带属性字段的结果就会触发反序列化失败。按下面任意一种方案处理即可:
- 方案一:升级SDK版本
把项目引用的Microsoft.Azure.CognitiveServices.Vision.Face升级到2.8.1-preview.1或更高版本,该预览版已经修复了UWP平台下的枚举序列化兼容问题。 - 方案二:不升级SDK,手动修改序列化配置
初始化IFaceClient实例时,手动给序列化设置加上字符串枚举转换器,覆盖默认配置即可,示例代码:using Newtonsoft.Json; using Newtonsoft.Json.Converters; // 初始化FaceClient client = new FaceClient(new ApiKeyServiceClientCredentials(你的订阅Key)) { Endpoint = 你的服务Endpoint, SerializationSettings = new JsonSerializerSettings { Converters = { new StringEnumConverter() } } }; - 构建配置校验
打包UWP安装包前,进入Player Settings > Other Settings > Configuration,把Api Compatibility Level设置为.NET Standard 2.1,避免IL2CPP编译时打包了错误版本的Newtonsoft.Json,引发额外的序列化逻辑异常。
修改完成后重新构建部署到HoloLens 2设备,即可正常解析包含人脸的接口返回结果。
内容的提问来源于stack exchange,提问作者Leado
相关产品推荐
相关产品推荐

