1. 程式人生 > >【學習OpenCV】通過DLL實現影象資料從.dat匯入Mat

【學習OpenCV】通過DLL實現影象資料從.dat匯入Mat

目的:主要為了將C++的影象處理部分交給C#介面,特此學習怎麼用DLL。

一、生成DLL

1、在vs中建立名為datFile的dll專案,設定包含目錄和庫目錄為opencv路徑

2、編寫datFile類的標頭檔案和實現

datFile.h

#ifndef DATFILE_H 
#define DATFILE_H

#include <iostream>  
#include <fstream>
#include "opencv2/highgui/highgui.hpp" 
#include "opencv2/gpu/gpu.hpp"
#include "opencv2/contrib/contrib.hpp"   //所用到的標頭檔案

#pragma comment( lib, "opencv_core249d.lib" )
#pragma comment( lib, "opencv_highgui249d.lib" )
#pragma comment( lib, "opencv_imgproc249d.lib" )
#pragma comment( lib, "opencv_gpu249d.lib" )
#pragma comment( lib, "opencv_contrib249d.lib" )  //所用到的lib

using namespace std;
using namespace cv;  //名稱空間

typedef int16_t datasize;  //影象資料大小

class _declspec(dllexport) datFile  //類宣告,dllexport表示從dll中匯出類
{
public:
	void read(const char* filename, Mat& src);  //從.dat匯出資料
	int16_t height;  
	int16_t width;   //影象尺寸
};

#endif 
datFile.cpp
#include "stdafx.h"
#include "datFile.h"

void datFile::read(const char* filename, Mat& src)
{
    <span style="white-space:pre">	</span>//輸入原始資料
	ifstream datfile(filename, ios::in|ios::binary);		
<span style="white-space:pre">	</span>datfile.read ((char*)&height, sizeof(int16_t));
	datfile.read ((char*)&width, sizeof(int16_t));	
	src.create(height, width, CV_16UC1);
	datfile.read ((char*)src.data, height*width*sizeof(datasize)); 
    <span style="white-space:pre">	</span>datfile.close();
}

分別新增到專案的標頭檔案和原始檔中,編譯,獲得datFile.dll和datFile.lib

二、呼叫DLL

1、建立名為testDll的控制檯專案,設定包含目錄和庫目錄為opencv路徑

2、把datFile.cpp拷貝至本目錄並新增標頭檔案

3、編寫測試程式碼。

testDll.cpp

#include "stdafx.h"
#include "readDat.h"  //包含類宣告標頭檔案  
#pragma comment(lib,"lib所在路徑\\datFile.lib")  //或者把lib拷貝至本目錄,直接填"datFile.lib"

int _tmain(int argc, _TCHAR* argv[])
{
	Mat src;
	datFile dat;
	dat.read("dat檔案所在路徑\\raw.dat",src);

	namedWindow("show",CV_WINDOW_NORMAL);
	resizeWindow("show",dat.height,dat.width);
	imshow("show",src);

	waitKey(0);
	return 0;
}

編譯,得到testDll.exe

4、將datFile.dll和相關的opencv的dll(包括tbb的lib)與testDll.exe放在同一個資料夾裡,那麼在別的沒有部署opencv的機器上也可以運行了