Search code examples
c#emgucvaccess-violationmat

'System.AccessViolationException' while assigning `Emgu.CV.Mat` to `Emgu.CV.UI.ImageBox` (Emgu)


Hi what I'm trying to do is assigning an Emgu.CV.Mat to an Emgu.CV.UI.ImageBox but I keep getting an System.AccessViolationException error within the CvInvokeCore.cs file (Line 2379 cveMinMaxLoc(iaArr, ref minVal, ref maxVal, ref minLoc, ref maxLoc, iaMask);):

An unhandled exception of type 'System.AccessViolationException' occurred in Emgu.CV.World.dll

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

The Code is pretty simple. I generate an Bitmap

Bitmap tmp = mybitmap.getBitmap(); // generates my Bitmap
pictureBox1.Image = tmp; // assigning it to an Win Form picture Box works pretty fine

imageBox1.Image = ConvertBitmapToMat(tmp); // but converting the Bitmap to an Mat file 
                                           // and try to assign it to an 
                                           // Emgu.CV.UI.ImageBox throws the
                                           // error in the above mentioned file.

The ConvertBitmapToMat() code I used is:

public Mat ConvertBitmapToMat(Bitmap bmp)
{
   // Lock the bitmap's bits.  
    Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);

    System.Drawing.Imaging.BitmapData bmpData =
        bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
            bmp.PixelFormat);

    // data = scan0 is a pointer to our memory block.
    IntPtr data = bmpData.Scan0;

    // step = stride = amount of bytes for a single line of the image
    int step = bmpData.Stride;

    // So you can try to get you Mat instance like this:
    Mat mat = new Mat(bmp.Height, bmp.Width, Emgu.CV.CvEnum.DepthType.Cv32F, 4, data, step);

    // Unlock the bits.
    bmp.UnlockBits(bmpData);

    return mat;
}

found at http://avidprogrammer.blogspot.de/2016/05/emgucv-c-convert-bitmap-object-to-mat.html

Any suggestions on this?


Solution

  • Use Image<>

    Bitmap tmp = mybitmap.getBitmap();
    Image<Bgr,Byte> img = new Image<Bgr,Byte>(tmp);
    imageBox1.Image = img;
    

    if you need Mat type, simply use img.Mat