Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Drawing.Image to Emgu.CV.Mat

Tags:

c#

emgucv

As titled. I am having a problem of converting System.Drawing.Image to Emgu.CV.Mat I tried to covert it from Drawing.Image to CV.Image but keep having Exceptions.

Is there any other solution available? Any help render is kindly appreciated.

like image 665
Kim McWing Wee Avatar asked Nov 02 '16 16:11

Kim McWing Wee


1 Answers

A OpenCV or EmguCV IMage has a Mat header in it. The trick I found was to get the System.Drawing.Image into a Image<>. If you are having trouble with exceptions be sure you are compiling for x64 if you are using EmguCV 3.1.

Here is a simple method to get a Mat object:

private Mat GetMatFromSDImage(System.Drawing.Image image)
{
    int stride = 0;
    Bitmap bmp = new Bitmap(image);

    System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height);
    System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);

    System.Drawing.Imaging.PixelFormat pf = bmp.PixelFormat;
    if (pf == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
    {
        stride = bmp.Width * 4;
    }
    else
    {
        stride = bmp.Width * 3;
    }

    Image<Bgra, byte> cvImage = new Image<Bgra, byte>(bmp.Width, bmp.Height, stride, (IntPtr)bmpData.Scan0);

    bmp.UnlockBits(bmpData);

    return cvImage.Mat;
}

Hope this helps! Doug

like image 56
AeroClassics Avatar answered Sep 28 '22 08:09

AeroClassics