从PC加载图像作为流

时间:2017-01-04 14:21:49

标签: c# uwp microsoft-cognitive

我正在尝试将PC上的图片作为原始图片加载,以便将其与Microsoft认知服务情感(UWP)一起使用。 下面是我的一段代码:

        //Chose Image from PC
    private async void chosefile_Click(object sender, RoutedEventArgs e)
    {


        //Open Dialog
        FileOpenPicker open = new FileOpenPicker();
        open.ViewMode = PickerViewMode.Thumbnail;
        open.SuggestedStartLocation = PickerLocationId.Desktop;
        open.FileTypeFilter.Add(".jpg");
        open.FileTypeFilter.Add(".jpeg");
        open.FileTypeFilter.Add(".gif");
        open.FileTypeFilter.Add(".png");
        file = await open.PickSingleFileAsync();


        if (file != null)
        {//imagestream is declared as IRandomAccessStream.

            imagestream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
            var image = new BitmapImage();
            image.SetSource(imagestream);
            imageView.Source = image;
        }
        else
        {
            //  
        }
    }

上面的部分工作正常,它从电脑(对话框)中选择一张照片并将其显示在图像框中。

    private async void analyse_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            emotionResult = await emotionServiceClient.RecognizeAsync(imagestream.AsStream());
        }
        catch
        {
            output.Text = "something is wrong in stream";
        }

        try { 
            if(emotionResult!= null)
            {
                Scores score = emotionResult[0].Scores;
                output.Text = "Your emotions are: \n" +
                    "Happiness: " + score.Happiness + "\n" +
                    "Sadness: " + score.Sadness;
            }
        }
        catch
        {
         output.Text = "Something went wrong";
        }
    }

我认为错误是由于imagestream.AsStream() imagestream声明为IRandomAccessStream。

有人可以告诉我如何修复该部分,如果错误实际上是由于没有正确加载图像?

编辑: 还有更好的方法来实现这一点,而不是使用流来传递emotionServiceClient一个保存的文件而不是流吗?

2 个答案:

答案 0 :(得分:0)

为什么不使用他们的示例,而不是试图将文件保存在内存中,为什么不保留路径,然后使用路径来读取流。

https://www.microsoft.com/cognitive-services/en-us/Emotion-api/documentation/GetStarted

在那里示例;

using (Stream imageFileStream = File.OpenRead(imageFilePath))
                {
                    //
                    // Detect the emotions in the URL
                    //
                    emotionResult = await emotionServiceClient.RecognizeAsync(imageFileStream);
                    return emotionResult;
                }

因此,您将捕获imageFilePath作为打开文件对话框的结果。

答案 1 :(得分:0)

您的问题是,您已经通过创建emotionServiceClient.RecognizeAsync来提升流媒体位置,因此在您拨打var stream = imagestream.AsStreamForRead(); stream.Position = 0; emotionResult = await emotionServiceClient.RecognizeAsync(stream); 时,您的阅读位置就在最后。因此,您需要回放':

{{1}}