优化自VM图像类型转换专题(C#篇),易读且好用。
社区的代码展示没有高亮,加上图片便于阅读。
注意如果是 vm 4.3 版本,ImageData 的高度属性的名字是 Heigth 😅
附上代码文字便于黏贴。
public ImageData MatToImageData(Mat mat)
{
ImageData img = new ImageData();
byte[] buffer = new Byte[mat.Width * mat.Height * mat.Channels()];
Marshal.Copy(mat.Ptr(0), buffer, 0, buffer.Length);
switch (mat.Channels())
{
case 1:
img.Buffer = buffer;
img.Width = mat.Width;
img.Height = mat.Height;
img.PixelFormat = ImagePixelFormate.MONO8;
break;
case 3:
for (int i = 0; i < buffer.Length - 2; i += 3)
{
byte temp = buffer[i];
buffer[i] = buffer[i + 2];
buffer[i + 2] = temp;
}
img.Buffer = buffer;
img.Width = mat.Width;
img.Height = mat.Height;
img.PixelFormat = ImagePixelFormate.RGB24;
break;
default:
throw new Exception(string.Format("Unsupported channels: {0}", mat.Channels()));
}
return img;
}
public Mat ImageDataToMat(ImageData img)
{
Mat mat = null;
switch (img.PixelFormat)
{
case ImagePixelFormate.MONO8:
mat = new Mat(img.Height, img.Width, MatType.CV_8UC1);
Marshal.Copy(img.Buffer, 0, mat.Ptr(0), img.Buffer.Length);
break;
case ImagePixelFormate.RGB24:
mat = new Mat(img.Height, img.Width, MatType.CV_8UC3);
Marshal.Copy(img.Buffer, 0, mat.Ptr(0), img.Buffer.Length);
Cv2.CvtColor(mat, mat, ColorConversionCodes.RGB2BGR);
break;
default:
throw new Exception("Unsupported vm-script img format!");
}
return mat;
}
FAQ-专题-图像转换 6 Mat 与脚本图像(ImageData)互转中也有这块代码,但 ImageDataToMat 实现得有问题。