Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

c# - converting byte array to Mat

I have a CCD driver which returns IntPtr to me. I used Marshal.Copy to byte array (bytearray_Image), each element inside bytearray_Image stores 8bit R/G/B value which the sequence is byte[0] = R value, byte[1] = G value, byte[2] = B value...and so on. I have successfully converted to 3 Channels Mat using below code snippet:

var src = new Mat(rows: nHeight, cols: nWidth, type: MatType.CV_8UC3); var indexer = src.GetGenericIndexer();

        int x = 0;
        int y = 0;
        for (int z = 0; z < (bytearray_Image.Length - 3); z += 3)
        {
            byte blue = bytearray_Image[(z + 2)];
            byte green = bytearray_Image[(z + 1)];
            byte red = bytearray_Image[(z + 0)];

            Vec3b newValue = new Vec3b(blue, green, red);
            indexer[y, x] = newValue;
            x += 1;

            if (x == nWidth)
            {
                x = 0;
                y += 1;
            }
        }

Since the image is very large, this method seems to be too slow to convert the image. Is there any ways to do such conversion efficiently?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This code works for me:

var image = new Mat(nHeight, nWidth, MatType.CV_8UC3);
int length = nHeight * nWidth * 3; // or image.Height * image.Step;
Marshal.Copy(bytearray_Image, 0, image.ImageData, length);

But it will work for you only if byte[] data's step length is equal to the Mat's


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...