【问题标题】:Convert a System.Drawing.Bitmap to Windows.Graphics.Imaging.SoftwareBitmap将 System.Drawing.Bitmap 转换为 Windows.Graphics.Imaging.SoftwareBitmap
【发布时间】:2019-10-21 12:16:24
【问题描述】:

我有一个 WPF 项目并将图像从 USB 相机捕获到 System.Drawing.Bitmap(我也可以捕获 System.Windows.Media.Imaging.BitmapSource)并且需要将其转换为 Windows.Graphics.Imaging .SoftwareBitmap 制作“VideoFrame”以与 Onnx 模型进行比较。

相机驱动程序是一个 .net 程序集,不会绑定到 uwp 项目。我尝试创建一个 .net 标准程序集来弥合差距,但没有成功。我只需要将位图转换为 SoftwareBitmap。请帮忙!

我使用此代码作为来自相机的位图图像的同情基础 - https://github.com/Azure-Samples/cognitive-services-onnx12-customvision-sample

【问题讨论】:

    标签: c# wpf uwp azure-cognitive-services


    【解决方案1】:

    没有直接转换。您需要从 System.Drawing.Bitmap 中提取图像数据,然后根据该数据创建新的 SoftwareBitmap。

    例如,您可以使用Save(Stream, ImageFormat) 方法将此图像以指定格式保存到指定流中。

    然后,您可以尝试调用BitmapDecoder.CreateAsync 方法从流中创建解码器。

    之后,您可以调用 GetSoftwareBitmapAsync 来获取 SoftwareBitmap 对象。

    以下是一个简单的代码示例:

    Bitmap bitmap = getyourbitmap();
    using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
    {
        bitmap.Save(stream.AsStream(),ImageFormat.Jpeg);//choose the specific image format by your own bitmap source
        Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
        SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();
    }
    

    【讨论】:

    • 谢谢,但我收到一个错误 'InMemoryRandomAccessStream' does not contain a definition for 'AsStream' 。我看起来像 - Save(System.IO.Stream 流,System.Drawing.Imaging.ImageFormat 格式)只是 System.IO.Stream。
    • @EricPhillips AsStream 是“System.Runtime.WindowsRuntime”中的扩展方法。请参阅Calling Windows 10 APIs From a Desktop Application 以添加对它的引用。根据该博客,一种简单的方法是为您的 WPF 应用程序安装“UwpDesktop”nuget 包,然后它会自动添加对它的引用。
    【解决方案2】:

    我发现您可以使用 Windows.Security.Cryptography 从图像数组字节创建 IBuffer。然后您可以将 IBuffer 复制到 SoftwareBitmap。

    using Windows.Security.Cryptography;
    
    IBuffer buffer = CryptographicBuffer.CreateFromByteArray(ImageByteArray);
    
    SoftwareBitmap softwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Gray8, 800, 600);
    softwareBitmap.CopyFromBuffer(buffer);
    VideoFrame inputImage = VideoFrame.CreateWithSoftwareBitmap(softwareBitmap);
    

    【讨论】:

      猜你喜欢
      • 2010-11-15
      • 1970-01-01
      • 2011-08-07
      • 2022-01-16
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多