从 PC 加载图像作为流

load image from PC as stream

我正在尝试从我的 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() 图像流被声明为 IRandomAccessStream。

谁能告诉我如何修复该部分,如果错误实际上是由于未正确加载图像造成的?

编辑: 还有没有更好的方法来做到这一点,而不是使用流向 emotionServiceClient 传递保存的文件而不是流?

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

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 作为打开文件对话框的结果。

您的问题是您通过创建 BitmapImage 提高了流的位置,因此在您调用 emotionServiceClient.RecognizeAsync 时您的阅读位置已经结束。所以你需要 'rewind':

var stream = imagestream.AsStreamForRead();
stream.Position = 0;
emotionResult = await emotionServiceClient.RecognizeAsync(stream);