C++使用opencv的mat图像,将mat传入OpencvCSharp的几种方法。
mat直接传入方法:
C++部分程序
cpp
extern "C" __declspec(dllexport) void MatToMat(cv::Mat& img)
{
img = cv::imread("E:\\OnnxTransEngine\\bus.jpg");
}
C#部分程序
cs
[DllImport("Dll1.dll", CallingConvention = CallingConvention.Cdecl)]
extern static public void MatToMat(IntPtr mat);
cs
Mat img = new Mat();
Class1.MatToMat(img.CvPtr);
Cv2.ImShow("img", img);
接下里介绍rgb图片和单通道图片传入方法,主要是将图片数据放入数组内,再传出。
RGB图片传入方法:
C++部分程序
cpp
extern "C" __declspec(dllexport) void MatToMatRgb(int& width, int& height, uchar* array)
{
cv::Mat matTemp = cv::imread("E:\\OnnxTransEngine\\bus.jpg");
//依次将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#部分程序
cs
[DllImport("Dll1.dll", CallingConvention = CallingConvention.Cdecl)]
extern static public void MatToMatRgb(ref int width, ref int height, ref byte array);
cs
int width = 0;
int height = 0;
byte[] datas = new byte[810 * 1080 * 3]; //根据图片实际尺寸来确定
Class1.MatToMatMonon(ref width, ref height, ref datas[0]);
Mat img = Mat.FromPixelData(height, width, MatType.CV_8UC3, datas);
Cv2.ImShow("img", img);
单图片传入方法:
C++部分程序
cpp
extern "C" __declspec(dllexport) void MatToMatMonon(int& width, int& height, uchar* array)
{
cv::Mat matTemp = cv::imread("E:\\OnnxTransEngine\\bus.jpg");
cv::cvtColor(matTemp, matTemp, cv::COLOR_BGR2GRAY);
//依次将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#部分程序
cs
[DllImport("Dll1.dll", CallingConvention = CallingConvention.Cdecl)]
extern static public void MatToMatMonon(ref int width, ref int height, ref byte array);
cs
int width = 0;
int height = 0;
byte[] datas = new byte[810 * 1080 * 1]; //根据图片实际尺寸来确定
Class1.MatToMatMonon(ref width, ref height, ref datas[0]);
Mat img = Mat.FromPixelData(height, width, MatType.CV_8UC1, datas);
Cv2.ImShow("img", img);