如何將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 <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);//沒有安裝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;
- }