将C++ IplImage 图像用C#读取

如何将C++ IplImage 图像用C#读取  ?

将opencv 的C++程序做成 dll 动态链接库 用C#调用 

当然这里需要安装emgucv  ,也可以自己实现这个类。

下面我把实现贴出来给大家参考:

1.制作dll    

  1. #include "stdafx.h"  
  2. #define DLL_API extern "C" _declspec(dllexport)     
  3. #include <Windows.h>    
  4. #include <stdio.h>    
  5. #include <opencv2\opencv.hpp>  
  6. #include <opencv\cxcore.h>  
  7. #include <opencv2/legacy/compat.hpp>  
  8. using namespace std;  
  9. using namespace cv;  
  10.   
  11. DLL_API IplImage * _stdcall run1()  
  12. {  
  13.   
  14.     IplImage *src;  
  15.     src = cvLoadImage("d:/1.jpg");  
  16.       
  17.     return src;  
  18. }  

 2.C#中读取dll

  需要开启 unsafe 模式

  1. [DllImport("dll_test_0410.dll")]  
  2.         unsafe  
  3.         public static extern MIplImage* run1();  
调用函数并显示成图片:

需要将生成的dll 放入c#工程的bin里面对应的debug或者release

  1. unsafe  
  2.        MIplImage* a;  
  3.        unsafe  
  4.        private void button5_Click(object sender, EventArgs e)  
  5.        {  
  6.            IntPtr aa= new IntPtr();  
  7.            a= run1();  
  8.            int m= a->width;  
  9.            aa = a->imageData;  
  10.            int uu =a->height;  
  11.            int step = a->widthStep;  
  12.            Image<Bgr, byte> src = new Image<Bgr, byte>(m, uu, step, aa);//没有安装emgucv的话这个方法不能用,用intPtr转换  
  13.            pictureBox1.Image =  src.ToBitmap();  
  14. ///////////////方法二,但是MIplImage还需要定义速度也慢,下面为单通道图像,多通道类似写一下就行//////  
  15.            byte []uuu = new byte[width*height];  
  16.            Marshal.Copy(aa,uuu,0,width*height);  
  17.            Bitmap dst = new Bitmap(width, height);  
  18.            Color color= new Color();  
  19.            for(int j=0;j<height;j++)  
  20.              
  21.            {for(int i=0;i<width;i++)  
  22.            {  
  23.                byte m = uuu[j*width+i];  
  24.                color = Color.FromArgb(m, m, m);  
  25.                dst.SetPixel(i, j, color);  
  26.            }  
  27.            }  
  28.              
  29.             pictureBox1.Image = dst;  
  30.   
  31.        }  
 
posted @ 2017-03-09 14:52  鹰杰  阅读(2316)  评论(0编辑  收藏  举报