Amin Ben Amin Ben - 3 months ago 33
C# Question

c# Emgu cv "SystemaccessViolationException" when split (for endianness bytes reverse in image buffer)

I want to read an image from a buffer as a 16 bits array, reverse the endianness, and show it as an image relative to some offsets (transformation from 16 bits to 8 bits). To do this I found the following solution in c++ and openCV (endianness reversing):

cv::Mat readFile()
{

std::ifstream input(Filename, std::ios::binary);
std::filebuf* buffer = input.rdbuf();

std::size_t size = buffer->pubseekoff(0, input.end, input.in);
buffer->pubseekpos(0, input.in);

char* charbuffer = new char[size];
buffer->sgetn(charbuffer, size);

input.close();

cv::Mat img = cv::Mat(512, 640, CV_8UC2, charbuffer);

//reverse Bytes
std::vector<cv::Mat> imgs(2);
cv::split(img, imgs);

imgs[0].convertTo(img, CV_16U, 256);
imgs[1].convertTo(imgs[1], CV_16U);
cv::Mat img16(512,640,CV_16U);

cv::add(img, imgs[1], img16);
return img16;
}


Now I'm trying to translate it to c# and Emgu CV (here I don't find as good documentation as openCV) My code is as follow:

public Image<Gray, byte> byteFilp( int height, int width, IntPtr buffer)
{

Mat img = new Mat(height, width, DepthType.Cv8U , 2, buffer, width * 8);

Mat[] imgs = new Mat[2];
imgs[0] = new Mat(height, width, DepthType.Cv8U , 1);
imgs[1] = new Mat(height, width, DepthType.Cv8U , 1);
CVinvoke.Split(img,imgs); // i ve tried "imgs = img.Split();" too, the same error result
Mat img16 = new Mat(height, width, DepthType.Cv16U, 1);
CvInvoke.Add(img, imgs[1], img16);
Image < Gray, byte> imgB = img16.ToImage<Gray, byte>();
return imgB;
}


I get this exception:

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


I'm using visual studio Ent 2015 with Emgu 3.1.

Answer

as Expected the problem is in my declaration also in the size of the row. the correction is as follow:

public  Image<Gray, byte> byteFilp( int height, int width, IntPtr buffer)
    {

        Mat img = new Mat(height, width, DepthType.Cv8U , 2, buffer,  width);

        Mat[] imgs = new Mat[2]; 
        imgs[0] = new Mat(height, width, DepthType.Cv8U , 1);
        imgs[1] = new Mat(height, width, DepthType.Cv8U , 1);
        CVinvoke.Split(img,imgs);
        imgs[0].ConvertTo(img,DepthType.Cv16U.1);
        imgs[1].ConvertTo(imgs[1],DepthType.Cv16U, 1);
        Mat img16 = new Mat(height, width, DepthType.Cv16U, 1);
        CvInvoke.Add(img, imgs[1], img16);
        Image < Gray, byte> imgB = img16.ToImage<Gray, byte>();
        return imgB;
    }