我无法显示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());
}
}
我需要从各种情绪的结果中找到最主要的情感。
答案 0 :(得分: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
并将scores
类替换为IDictionary<string, double>
。这是因为您不仅仅想要每个情感的属性。您想要一个可以设置的集合排序以找到最高的情感。(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<string,double>
包含得分,所以你可以显示它们并找到得分最高的情绪。