将opencv 的C++程序做成 dll 动态链接库 用C#调用
当然这里需要安装emgucv ,也可以自己实现这个类。
下面我把实现贴出来给大家参考:
1.制作dll
- #include "stdafx.h"
- #define DLL_API extern "C" _declspec(dllexport)
- #include <Windows.h>
- #include <stdio.h>
- #include <opencv2\opencv.hpp>
- #include <opencv\cxcore.h>
- #include <opencv2/legacy/compat.hpp>
- using namespace std;
- using namespace cv;
-
- DLL_API IplImage * _stdcall run1()
- {
-
- IplImage *src;
- src = cvLoadImage("d:/1.jpg");
-
- return src;
- }
2.C#中读取dll
需要开启 unsafe 模式
- [DllImport("dll_test_0410.dll")]
- unsafe
- public static extern MIplImage* run1();
调用函数并显示成图片:
需要将生成的dll 放入c#工程的bin里面对应的debug或者release
- unsafe
- MIplImage* a;
- unsafe
- private void button5_Click(object sender, EventArgs e)
- {
- IntPtr aa= new IntPtr();
- a= run1();
- int m= a->width;
- aa = a->imageData;
- int uu =a->height;
- int step = a->widthStep;
- Image<Bgr, byte> src = new Image<Bgr, byte>(m, uu, step, aa);
- pictureBox1.Image = src.ToBitmap();
- byte []uuu = new byte[width*height];
- Marshal.Copy(aa,uuu,0,width*height);
- Bitmap dst = new Bitmap(width, height);
- Color color= new Color();
- for(int j=0;j<height;j++)
-
- {for(int i=0;i<width;i++)
- {
- byte m = uuu[j*width+i];
- color = Color.FromArgb(m, m, m);
- dst.SetPixel(i, j, color);
- }
- }
-
- pictureBox1.Image = dst;
-
- }