Attention:本文方法需要配套使用
1.利用Cv2.imencode() 和 imdecode():
public Mat ByteToMat(byte[] Picture)
{
Mat imageData = new Mat();
imageData = Cv2.ImDecode(Picture, ImreadModes.Color);
return imageData;
}
public byte[] MatToByte(Mat Picture)
{
byte[] encodedImage = new byte[Picture.Width * Picture.Height * 3];
Cv2.ImEncode(".jpg", Picture, out encodedImage);
return encodedImage;
}
a 和 b 是图片的尺寸,可以先随意设大一点,然后根据imageData实际尺寸固定死。
public Mat ByteToMat_m1(byte[] Picture, int a, int b)
{
Mat imageData = new Mat(a, b,MatType.CV_8UC3);
int length = Picture.Length;// mats.Rows * mats.Cols * 3;
Marshal.Copy(Picture, 0, imageData.Data, length);
return imageData;
}
public byte[] MatToByte(Mat Picture)
{
var bytes = new byte[Picture.Total() * 3];//这里必须乘以通道数,不然数组越界,也可以用w*h*c,差不多
Marshal.Copy(Picture.Data, bytes, 0, bytes.Length);
return bytes;
}
需要注意的是,上述两组方法可能不能交叉使用,指针指错了造成内存损坏然后程序崩溃
3.总结,制作为类:
public class image_byte
{
public byte[] ImageToByte(System.Drawing.Image Picture)
{
MemoryStream ms = new MemoryStream();
if (Picture == null)
return new byte[ms.Length];
Picture.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] BPicture = new byte[ms.Length];
BPicture = ms.GetBuffer();
return BPicture;
}
public System.Drawing.Image ByteToImage(byte[] btImage)
{
if (btImage.Length == 0)
return null;
System.IO.MemoryStream ms = new System.IO.MemoryStream(btImage);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
return image;
}
public byte[] MatToByte_m1(Mat Picture)
{
var bytes = new byte[Picture.Total() * 3];//这里必须乘以通道数,不然数组越界,也可以用w*h*c,差不多
Marshal.Copy(Picture.Data, bytes, 0, bytes.Length);
return bytes;
}
public Mat ByteToMat_m1(byte[] Picture, int a, int b)
{
Mat imageData = new Mat(a, b,MatType.CV_8UC3);
int length = Picture.Length;// mats.Rows * mats.Cols * 3;
Marshal.Copy(Picture, 0, imageData.Data, length);
return imageData;
}
public byte[] MatToByte_m2(Mat Picture)
{
byte[] encodedImage = new byte[Picture.Width * Picture.Height * 3];
Cv2.ImEncode(".jpg", Picture, out encodedImage);
return encodedImage;
}
public Mat ByteToMat_m2(byte[] Picture)
{
Mat imageData = new Mat();
imageData = Cv2.ImDecode(Picture, ImreadModes.Color);
return imageData;
}
}
测试上述程序,将下列程序粘贴到一个button下:
Mat data = Cv2.ImRead("mashixing.jpg");//替换图片地址
// 编码图像数据为 JPEG 格式
byte[] encodedImage = new byte[data.Width * data.Height * 3];
image_byte image_Byte = new image_byte();
encodedImage = image_Byte.MatToByte_m1(data);
Mat image = image_Byte.ByteToMat_m1(encodedImage, data.Rows, data.Cols);
byte[] bytes = image_Byte.MatToByte_m2(data);
Mat mat = image_Byte.ByteToMat_m2(bytes);
Cv2.ImShow("1", data);
Cv2.ImShow("2", image);
Cv2.ImShow("3", mat);
END