如何将 C# WritableBitmap 转换为 EmguCV/OpenCV Mat?

How do you convert a C# WritableBitmap to a EmguCV/OpenCV Mat?

我有一个 WritableBitmap,我想将它转换为 EmguCV/OpenCV Mat。我该怎么做呢?我已经从在线代码中尝试了几种链解决方案(WritableBitmap -> Bitmap -> Map),但我还没有找到任何有效的方法。谢谢!

我发现这很好用:

    public static Mat ToMat(BitmapSource source)
    {
        if (source.Format == PixelFormats.Bgra32)
        {
            Mat result = new Mat();
            result.Create(source.PixelHeight, source.PixelWidth, DepthType.Cv8U, 4);
            source.CopyPixels(Int32Rect.Empty, result.DataPointer, result.Step * result.Rows, result.Step);
            return result;
        }
        else if (source.Format == PixelFormats.Bgr24)
        {
            Mat result = new Mat();
            result.Create(source.PixelHeight, source.PixelWidth, DepthType.Cv8U, 3);
            source.CopyPixels(Int32Rect.Empty, result.DataPointer, result.Step * result.Rows, result.Step);
            return result;
        }
        else if (source.Format == PixelFormats.Pbgra32)
        {
            Mat result = new Mat();
            result.Create(source.PixelHeight, source.PixelWidth, DepthType.Cv8U, 4);
            source.CopyPixels(Int32Rect.Empty, result.DataPointer, result.Step * result.Rows, result.Step);
            return result;
        }
        else
        {
            throw new Exception(String.Format("Conversion from BitmapSource of format {0} is not supported.", source.Format));
        }
    }

道格