C++将OpenCV的图片传入主要是将图片信息放入uchar数组中,C#再使用byte数组读取信息,生成图片。
RGB图片传入方法:
C++部分程序
extern "C" __declspec(dllexport) void MatToHobject(int& width, int& height, uchar * array)
{
Mat matTemp;
//依次将rgb数据放入uchar数组中
for (int i = 0; i < matTemp.rows; i++) {
for (int j = 0; j < matTemp.cols; j++) {
for (int k = 0; k < 3; k++) {
array[i * matTemp.cols * 3 + j * 3 + k] = matTemp.at<cv::Vec3b>(i, j)[k];
}
}
}
//将图片的宽高传出
width = matTemp.cols;
height = matTemp.rows;
}
C#部分程序
//C#调用C++程序
[DllImport("Dll1.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void MatToHobject(ref int width, ref int height, ref byte array);
//使用byte数组存放
byte[] Array = new byte[1200 * 916 * 3]; //图片的宽*高*3通道
int Width, height;
//读取byte数组
MatToHobject(ref width, ref height, ref Array[0]);
//生成图片
BytetoHobject(Array, width, height, out h_Image);
//生成函数
private void BytetoHobject(byte[] rawValues, int width, int height, out HObject Image)
{
Image = null;
Bitmap bmp = null;
try
{
bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
BitmapData bmpData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
IntPtr iptr = bmpData.Scan0; // 获取bmpData的内存起始位置
System.Runtime.InteropServices.Marshal.Copy(rawValues, 0, iptr, width * height * 3);
HOperatorSet.GenImageInterleaved(out Image, (HTuple)iptr, "rgb", width, height, 0, "byte", 0, 0, 0, 0, -1, 0);
bmp.UnlockBits(bmpData);
bmp.Dispose();
}
catch (Exception e)
{
}
}
单通道图片传入方法:
C++部分程序
extern "C" __declspec(dllexport) void MatToHobject(int& width, int& height, uchar * array)
{
Mat matTemp;
//依次将rgb数据放入uchar数组中
for (int i = 0; i < matTemp.rows; i++) {
for (int j = 0; j < matTemp.cols; j++) {
array[i * matTemp.cols + j] = matTemp.at<uchar>(i, j);
}
}
//将图片的宽高传出
width = matTemp.cols;
height = matTemp.rows;
}
C#部分程序
//C#调用C++程序
[DllImport("Dll1.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void MatToHobject(ref int width, ref int height, ref byte array);
//使用byte数组存放
byte[] Array = new byte[1200 * 916]; //图片的宽*高
int Width, height;
//读取byte数组
MatToHobject(ref width, ref height, ref Array[0]);
//生成图片
BytetoHobject(Array, width, height, out h_Image);
//生成函数
private void BytetoHobject(byte[] rawValues, int width, int height, out HObject Image)
{
Image = null;
Bitmap bmp = null;
try
{
bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
BitmapData bmpData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
IntPtr iptr = bmpData.Scan0; // 获取bmpData的内存起始位置
System.Runtime.InteropServices.Marshal.Copy(rawValues, 0, iptr, width * height * 3);
HOperatorSet.GenImage1(out Image, "byte", width, height, (HTuple)iptr);
bmp.UnlockBits(bmpData);
bmp.Dispose();
}
catch (Exception e)
{
}
}