一、将C代码生成DLL
首先新建一个项目,选择 win32项目,如下图所示:
点击确定,下一步后,选择 DLL,导出符号,如下图所示:
点击完成,就可以将自己添加想要封装成DLL的代码。
如:我想要将利用opencv查找人脸的代码,封装成DLL,在C#下调用
首先,我在DllTest.h文件中添加函数:
extern "C" DLL_FACE_API HBITMAP FindFaceForCSharp(int EnableCamera,char str[50],int *CooIndex,int* width, int* height,
double scale_factor,int min_neighbors,int min_size);
然后在.cpp中实现函数:
//@PARAM:EnableCamera:if true open the camera;
//@PARAM:*CoorIndex:coordination array, a[0] index total number of faces;then x point, y point width, height and loop
//@PARAM:*width :return picture width
//@PARAM:*height: return picture height
HBITMAP FindFaceForCSharp(int EnableCamera,char Videoname[50],int *CooIndex,int* width, int* height,double scale_factor,int min_neighbors,int min_size)
{
if (EnableCamera)
{
static int active=0;
active++;
int i=0;
int j=0;
if(active==1)
{
if(EnableCamera==1)
m_Video=cvCaptureFromCAM(0);
else
m_Video=cvCaptureFromFile(Videoname);
cascade1=(CvHaarClassifierCascade*)cvLoad("haarcascade_frontalface_alt2.xml");
cascade2=(CvHaarClassifierCascade*)cvLoad("haarcascade_frontalface_alt.xml");
cascade3=(CvHaarClassifierCascade*)cvLoad("haarcascade_profileface.xml"); // detect face datafile
}
if (!m_Video)
{
fprintf(stderr,"can not open camera\n");
return NULL;
}
if(Frame=cvQueryFrame(m_Video))
{
*width=Frame->width;
*height=Frame->height;
CvRect FaceRect[100];// the temp face rect
CvPoint pt[100];// the before face center point
for (int i=0;i<100;i++)
{
FaceRect[i].x=0;FaceRect[i].y=0;
FaceRect[i].width=0;FaceRect[i].height=0;
pt[i].x=0;pt[i].y=0;
}
//ǰһ֡ÈËÁ³µÄÖÐÐÄ
int TotalBef=0;
if (CooIndex[0]>0)
{
TotalBef=CooIndex[0];
for (i=1,j=0;j<TotalBef;i=i+5,j++)
{
pt[j].x=CooIndex[i]+CooIndex[i+2]/2;
pt[j].y=CooIndex[i+1]+CooIndex[i+3]/2;
}
}
IplImage *image=cvCloneImage(Frame);
if(image->origin==1)
cvFlip(image,NULL,0); //////////////////////////////////////////
int facetotal=0;// face count
//find skin
IplImage *Skin=cvCreateImage(cvGetSize(Frame),8,1);
{
int x,y;
int b,g,r;
float Y,Cr,Cb;
cvZero(Skin);
for (x=0;x<Frame->height;x++)
for (y=0;y<Frame->width;y++)
{
b=((uchar*)(Frame->imageData+Frame->widthStep*x))[y*3];
g=((uchar*)(Frame->imageData+Frame->widthStep*x))[y*3+1];
r=((uchar*)(Frame->imageData+Frame->widthStep*x))[y*3+2];
Y=(float)(0.299*r+0.587*g+0.114*b);
Cr=(float)(0.5*r-0.419*g-0.081*b+128.0);
Cb=(float)(-0.169*r-0.331*g+0.5*b+128.0);
if (Cr/Cb>1.05)
{
if ((Cr>132&& Cr<178)&&(Cb>87 &&Cb<126))
{
((uchar*)(Skin->imageData+Skin->widthStep*x))[y]=255;
}
}
}
cvSmooth(Skin,Skin,CV_BLUR,3,3);
cvErode(Skin,Skin,0,1);
cvDilate(Skin,Skin,0,1);
}
if(Skin->origin==0)
cvFlip(Skin,NULL,0);//////////////////////////////////////////////////////////////////////
// cvNamedWindow("skin",1);
// cvShowImage("skin",Skin);
//detect face
{
CvRect bndRect = cvRect(0,0,0,0);
IplImage* binal_copy=cvCloneImage(Skin);
double scale = 1.3;
double bndArea=0;
int i=0;
int flags=8;
int maxradius=0;
CvMemStorage* storage_face=cvCreateMemStorage(0);
CvSeq* contour;
cvFindContours( binal_copy, storage_face, &contour, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
for( ; contour != 0; contour = contour->h_next )
{
bndRect=cvBoundingRect(contour,0);
bndArea=fabs(cvContourArea(contour,CV_WHOLE_SEQ));
if (bndRect.width<10||bndRect.height<10/*||bndArea<100||(double)bndRect.width/bndRect.height>2.5||(double)bndRect.width/bndRect.height<0.4*/)
{
continue;
}
if (bndRect.height<binal_copy->height/5&&bndRect.width<binal_copy->width/5)
{
bndRect = cvRect(bndRect.x - bndRect.width/4, bndRect.y - bndRect.height/4
, bndRect.width*1.5, bndRect.height*1.5);
}
if (bndRect.x<0||bndRect.y<0||bndRect.width<0||bndRect.height<0)
{
bndRect=cvBoundingRect(contour,0);
}
cvSetImageROI(image, bndRect);
cvSetImageROI(Skin,bndRect);
IplImage* small_img = cvCreateImage( cvSize( cvRound (image->roi->width/scale),cvRound (image->roi->height/scale)),8, 3 );
cvResize( image, small_img, CV_INTER_LINEAR );
//cvEqualizeHist( small_img, small_img );
IplImage *Img_B=cvCreateImage(cvGetSize(small_img),8,1);
IplImage *Img_R=cvCreateImage(cvGetSize(small_img),8,1);
IplImage *Img_G=cvCreateImage(cvGetSize(small_img),8,1);
cvSplit(small_img,Img_B,Img_R,Img_G,NULL);
cvResetImageROI( image );
if( cascade1&&cascade2)
{
CvSeq* faces = cvHaarDetectObjects( Img_R, cascade1, storage_face,
scale_factor,min_neighbors, 0/*CV_HAAR_DO_CANNY_PRUNING*/,cvSize(min_size, min_size) );
if (!faces->total)
{
faces=cvHaarDetectObjects(small_img,cascade2,storage_face,1.1,2,0,cvSize(50,50));
}
if (!faces->total)
{
faces=cvHaarDetectObjects(small_img,cascade3,storage_face,1.2,3,0,cvSize(50,50));
}
for( i = 0; i < (faces ? faces->total : 0); i++ )
{
CvRect *r = (CvRect*)cvGetSeqElem( faces, i);
CvRect realR=cvRect(0,0,0,0);
realR.x=r->x*scale+bndRect.x;
realR.y=image->height-(r->y*scale+bndRect.y);
realR.width=r->width*scale;
realR.height=r->height*scale;
realR.y=realR.y-realR.height;
//½«Öظ´Ñ¡ÔñÔÚÒ»¸öÈËÁ³ÇøÓòµÄ¾ØÐÎÈ¥µô
bool exist=false;
for (int j=0;j<facetotal;j++)
{
if (FaceRect[j].x<(realR.x+realR.width/2)&&(realR.x+realR.width/2)<FaceRect[j].x+FaceRect[j].width)
{
exist=true;
break;
}
}
if(exist)
continue;
FaceRect[facetotal++]=realR; // output the all face area
cvRectangle(Frame,cvPoint(realR.x,realR.y),
cvPoint(realR.x+realR.width,realR.y+realR.height),CV_RGB(0,255,0),2,8,0);
}
}
cvResetImageROI(Skin);
cvReleaseImage(&small_img);
cvReleaseImage(&Img_B);
cvReleaseImage(&Img_R);
cvReleaseImage(&Img_G);
}
cvReleaseImage(&binal_copy);
cvReleaseMemStorage(&storage_face);
}
cvReleaseImage(&Skin);
cvReleaseImage(&image);
Rect_x_QSort(FaceRect,0,facetotal-1);
//Êä³öµÄÊý¾Ý½á¹¹£¬·Ö±ðΪÈËÁ³ÖÐÐÄ£¬ÒÔ¼°Õæ¼ÙÅжÏÊÇ·ñΪ¸ú×Ùʼþ
CooIndex[0]=facetotal;
for (i=0,j=0;j<facetotal;i=i+5,j++)
{
CooIndex[i+1]=FaceRect[j].x;
CooIndex[i+2]=FaceRect[j].y;
CooIndex[i+3]=FaceRect[j].width;
CooIndex[i+4]=FaceRect[j].height;
CooIndex[i+5]=0;
}
//¸ù¾ÝÅ·¼¸ÀïµÃ¶¨Àí£¬Åжϸú×Ùʼþ
if (TotalBef>0)
{
for ( i=0;i<facetotal;i++)
{
float distance=0.;
for ( j=0;j<TotalBef;j++)
{
float x=0,y=0;
x=FaceRect[i].x+FaceRect[i].width/2-pt[j].x;
y=FaceRect[i].y+FaceRect[i].height/2-pt[j].y;
distance=sqrt(pow(x,2)+pow(y,2));
if (distance<30)
{
CooIndex[5*i+5]=1;
}
}
}
}
cvFlip(Frame,NULL,0);
// transfer iplimage to HBITMAP
{
HDC hDC = ::CreateCompatibleDC(0);
BYTE tmp[sizeof(BITMAPINFO)+255*4];
BITMAPINFO *bmi = (BITMAPINFO*)tmp;
HBITMAP hBmp;
int i;
memset(bmi,0,sizeof(BITMAPINFO));
bmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi->bmiHeader.biWidth = Frame->width;
bmi->bmiHeader.biHeight = Frame->height;
bmi->bmiHeader.biPlanes = 1/*Size*/;
bmi->bmiHeader.biBitCount = Frame->nChannels * Frame->depth;
bmi->bmiHeader.biCompression = BI_RGB;
bmi->bmiHeader.biSizeImage = Frame->width*Frame->height*1;
bmi->bmiHeader.biClrImportant =0 ;
switch(Frame->nChannels * Frame->depth)
{
case 8 :
for(i=0 ; i < 256 ; i++)
{
bmi->bmiColors[i].rgbBlue = i;
bmi->bmiColors[i].rgbGreen= i;
bmi->bmiColors[i].rgbRed= i;
}
break;
case 32:
case 24:
((DWORD*) bmi->bmiColors)[0] = 0x00FF0000; /* red mask */
((DWORD*) bmi->bmiColors)[1] = 0x0000FF00; /* green mask */
((DWORD*) bmi->bmiColors)[2] = 0x000000FF; /* blue mask */
break;
}
hBmp = ::CreateDIBSection(hDC,bmi,DIB_RGB_COLORS,NULL,0,0);
SetDIBits(hDC,hBmp,0,Frame->height,Frame->imageData,bmi,DIB_RGB_COLORS);
::DeleteDC(hDC);
return hBmp;
}
}
}
else
{
cvReleaseCapture(&m_Video);
m_Video=NULL;
}
return NULL;
}
编译后就可以在Debug或release下找到DLL了
二、在C#中调用DLL
将DLL拷贝到工程目录下,并添加导入代码:
[DllImport("DLL_face120203.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "FindFaceForCSharp")]
unsafe public static extern IntPtr FindFaceForCSharp(int EnableCamera, char []Videoname, int* CooIndex, ref int width,
ref int height, double scale_factor, int min_neighbors, int min_size,ref int count,bool validity);
完成上述操作后,就可以在C#下调用DLL封装的函数了。
如:
private void ProcessFrame(object sender, EventArgs arg)
{
#region unsafe module
unsafe
{
int EnableCamera =2; //为1时开启摄像头,屏蔽读视频文件; 为2时关闭摄像头,开始读视频文件
string file = Application.StartupPath + "\\PicNew\\test1.avi";
char[] videoName = file.ToCharArray();
int ImgWidth = 0;
int ImgHeight = 0;
int* Coordination = stackalloc int[500];
double min_factor = 1.05;
int min_neighbor = 3;
int size = 37;
/*************************************************************************************************/
/* EnableCamera: 摄像头的状态 1:打开摄像头,2:打开视频 */
/* Videoname:视频文件 */
&n