【问题标题】:Displaying Project Oxford's Emotion API result in C#在 C# 中显示 Project Oxford 的 Emotion API 结果
【发布时间】:2016-07-22 15:48:09
【问题描述】:

我无法显示 Emotion API 返回的结果。结果以 Emotion[] 的形式返回。代码如下

    private async void button2_Click(object sender, EventArgs e)
    {
        try
        {
            pictureBox2.Image = (Bitmap)pictureBox1.Image.Clone();
            String s = System.Windows.Forms.Application.StartupPath + "\\" + "emotion.jpg";
            pictureBox2.Image.Save(s);

            string imageFilePath = s;// System.Windows.Forms.Application.StartupPath + "\\" + "testing.jpg"; 
            Uri fileUri = new Uri(imageFilePath);

            BitmapImage bitmapSource = new BitmapImage();
            bitmapSource.BeginInit();
            bitmapSource.CacheOption = BitmapCacheOption.None;
            bitmapSource.UriSource = fileUri;
            bitmapSource.EndInit();

         //   _emotionDetectionUserControl.ImageUri = fileUri;
           // _emotionDetectionUserControl.Image = bitmapSource;

            System.Windows.MessageBox.Show("Detecting...");

            ***Emotion[] emotionResult*** = await UploadAndDetectEmotions(imageFilePath);

            System.Windows.MessageBox.Show("Detection Done");

        }
        catch (Exception ex)
        {
            System.Windows.MessageBox.Show(ex.ToString());
        }
    }

我需要从各种情绪的结果中找到最主要的情绪。

【问题讨论】:

    标签: c# api emotion microsoft-cognitive


    【解决方案1】:

    我去了API reference。它像这样返回 JSON:

    [
      {
        "faceRectangle": {
          "left": 68,
          "top": 97,
          "width": 64,
          "height": 97
        },
        "scores": {
          "anger": 0.00300731952,
          "contempt": 5.14648448E-08,
          "disgust": 9.180124E-06,
          "fear": 0.0001912825,
          "happiness": 0.9875571,
          "neutral": 0.0009861537,
          "sadness": 1.889955E-05,
          "surprise": 0.008229999
        }
      }
    ]
    

    我将它粘贴到http://json2csharp.com/ 中,它为我生成了一些类。 (我将根类重命名为 Emotion 并用 IDictionary<string, double> 替换了 scores 类。这是因为您不只是想要每种情绪的属性。您需要一个可以排序以找到最高情绪的集合. (IDictionary<string, double> 是最容易将 json 反序列化成的东西。)

    public class FaceRectangle
    {
        public int left { get; set; }
        public int top { get; set; }
        public int width { get; set; }
        public int height { get; set; }
    }
    
    public class Emotion
    {
        public FaceRectangle faceRectangle { get; set; }
        public IDictionary<string, double> scores { get; set; }
    }
    

    然后我编写了一个单元测试并从 Microsoft 的 API 页面粘贴到 JSON 中,看看我是否可以反序列化它。我添加了Newtsonsoft.Json Nuget package 并写道:

    [TestClass]
    public class DeserializeEmotion
    {
        [TestMethod]
        public void DeserializeEmotions()
        {
            var emotions = JsonConvert.DeserializeObject<Emotion[]>(JSON);
            var scores = emotions[0].scores;
            var highestScore = scores.Values.OrderByDescending(score => score).First();
            //probably a more elegant way to do this.
            var highestEmotion = scores.Keys.First(key => scores[key] == highestScore);
            Assert.AreEqual("happiness", highestEmotion);
        }
    
        private const string JSON =
            "[{'faceRectangle': {'left': 68,'top': 97,'width': 64,'height': 97},'scores': {'anger': 0.00300731952,'contempt': 5.14648448E-08,'disgust': 9.180124E-06,'fear': 0.0001912825,'happiness': 0.9875571,'neutral': 0.0009861537,'sadness': 1.889955E-05,'surprise': 0.008229999}}]";
    
    }
    

    测试通过了,就是这样。您有一个包含分数的Dictionary&lt;string,double&gt;,因此您既可以显示它们,也可以找到分数最高的情感。

    【讨论】:

    • 我确实在 Emotion API 示例的文件中找到了这些类定义,但问题是即使使用内置命令,我也无法将其转换为 Dictionary 或 List。我想必须有一种方法可以避免与 Microsoft.ProjectOxford.Emotion.Contract 文件中的类定义冲突。
    • Scott 的建议非常好,但如果您已经在使用客户端 SDK,则需要将 Emotion[] 序列化为字符串并返回到 other Emotion[]。另一种选择是这样的:var top = emotions.Select(emotion =&gt; { var dict = new Dictionary&lt;string, float&gt;(); foreach (var property in typeof(Scores).GetProperties()) { dict.Add(property.Name, (float)property.GetValue(emotion.Scores)); } return dict.OrderByDescending(kv =&gt; kv.Value).ThenBy(kv =&gt; kv.Key).First(); });
    • @ScottHannen 我的项目正在运行,谢谢您的帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 2017-03-24
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    相关资源
    最近更新 更多