简体   繁体   English

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

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

I have a WritableBitmap, and I would like to convert it to a EmguCV/OpenCV Mat. 我有一个WritableBitmap,我想将它转换为EmguCV / OpenCV Mat。 How would I go about doing that? 我该怎么做呢? I've tried several chain solutions (WritableBitmap -> Bitmap -> Map) from code online, but I haven't found anything that works. 我已经从代码在线尝试了几个链解决方案(WritableBitmap - > Bitmap - > Map),但我没有找到任何有效的方法。 Thanks! 谢谢!

I find this works pretty well: 我觉得这很有效:

    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));
        }
    }

Doug 道格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM