如何将C++ IplImage 图像用C#读取 ?
将opencv 的C++程序做成 dll 动态链接库 用C#调用
当然这里需要安装emgucv ,也可以自己实现这个类。
下面我把实现贴出来给大家参考:
1.制作dll
- #include "stdafx.h"
- #define DLL_API extern "C" _declspec(dllexport)
- #include <Windows.h>
- #include <stdio.h>
- #include <opencv2opencv.hpp>
- #include <opencvcxcore.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);//没有安装emgucv的话这个方法不能用,用intPtr转换
- pictureBox1.Image = src.ToBitmap();
- ///////////////方法二,但是MIplImage还需要定义速度也慢,下面为单通道图像,多通道类似写一下就行//////
- 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;
- }