Search code examples
c#opencvemgucvmatwriteablebitmap

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. 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. Thanks!


Solution

  • 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