【OpenCVSharp Mat和byte[]互相转换】

【OpenCVSharp Mat和byte[]互相转换】_第1张图片

版本:opencvsharp-4.5.3.20211228

我们以三通道图片为例:

1:Mat->byte[]

            Mat mat = Cv2.ImRead(fullpath);//Mat默认通道顺序是Bgr,和Bitmap一致
            var bytes = new byte[mat.Total()*3];//这里必须乘以通道数,不然数组越界,也可以用w*h*c,差不多
            Marshal.Copy(mat.Data, bytes, 0, bytes.Length);

2:byte[]->Mat

            var src = new Mat(height, width, MatType.CV_8UC3);
            int length = height * width * 3; // or src.Height * src.Step;
            Marshal.Copy(data, 0, src.Data, length);

其中,宽高可以这样获取:

            var height = mat.Rows;
            var width = mat.Cols;
            var channels = mat.Channels();
            var mattype = mat.Type();

PS:如果是对于Bitmap的图片,推荐用官方的包里的方法去转换不会出错:OpenCvSharp.Extensions.dll
里面有Bitmap和Mat的互相转换

Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(image); //bitmap转 mat
Bitmap bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat); // mat 转 bitmap

PS:CPP版可以参考https://blog.csdn.net/ImgLearning/article/details/79924676,其中byte 为unsigned char的宏

PS:另外用Unity的小伙伴还可以把Color32[]转化为指针,和OpenCVSharp或Native数据交流

var pixels = texture2D.GetPixels32();
GCHandle pixelHandle = GCHandle.Alloc(pixels, GCHandleType.Pinned); 
IntPtr pixelPointer = pixelHandle.AddrOfPinnedObject();

ref:
https://github.com/shimat/opencvsharp/issues/173
https://wiki.onakasuita.org/pukiwiki/?OpenCvSharp.Mat
https://blog.csdn.net/qq_36390344/article/details/105029771

你可能感兴趣的:(图片处理,opencv,计算机视觉)