C++生成人脸识别dll(C++ && C# 混合编程)

【Detect.h】

#ifndef DETECT_H_
#define DETECT_H_
#ifdef __cplusplus
#include 
#include 
#include 
#pragma comment(lib, "opencv_core2413.lib")
#pragma comment(lib, "opencv_imgproc2413.lib")
#pragma comment(lib, "opencv_objdetect2413.lib")
using namespace cv;
using namespace std;
#endif
class Detect
{
public :
    Mat img;
    Detect();
    list get_face_rect(Mat img); // 从gray上获取到位置,再在原图上截取下图片
    ~Detect();
private :
    Mat img_gray;
    vector<Rect> faces;
    vector<Rect> detectFaces(Mat img);
};
#endif

 

【Detect.cpp】

#include "stdafx.h"
#include "Detect.h"
#include <direct.h>
Detect::Detect(){}
list<int> Detect::get_face_rect(Mat img)
{
    cvtColor(img,img_gray,COLOR_BGR2GRAY);  //转换成灰度图
    equalizeHist(img_gray,img_gray);    //均衡化灰度图
    typedef list<int> LISTINT;
    LISTINT listInt;
    LISTINT::iterator i;
    faces = detectFaces(img_gray);  //在灰度图上识别出人脸
    for(size_t i=0; i<faces.size();i++){
        int x = faces[i].x; //脸部中心的x位置
        int y = faces[i].y; //脸部中心的y位置
        int width = faces[i].width; //脸部区域的宽度
        int heigh = faces[i].height;    //脸部区域的高度
        listInt.insert (listInt.end(), x);
        listInt.insert (listInt.end(), y);
        listInt.insert (listInt.end(), width);
        listInt.insert (listInt.end(), heigh);
    }
    return listInt;
}
vector<Rect> Detect::detectFaces(Mat img) //识别人脸
{
    CascadeClassifier faces_cascade;
    string path;
    const char *pc =  _getcwd(NULL, 0);
    path = pc;
    string face_date_name;
    string Link = path + "\\" + "haarcascade_frontalface_alt.xml"; // 人脸识别库直接就放在与生成的软件统一路径下就可以了
    faces_cascade.load(Link); 
    faces_cascade.detectMultiScale(img,faces,1.6, 2, 0|CV_HAAR_SCALE_IMAGE, Size(200, 200) );
    return faces;
}
Detect::~Detect(){}

【Detect_face.cpp】

// Detect_face.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
#include "Detect.h"
int main()
{
    return 0;
}
extern "C"_declspec(dllexport) bool matrix(HBITMAP Bmp,int *N);
bool __declspec(dllexport) matrix(HBITMAP Bmp,int *N)
{
    BITMAP bmp;
    GetObject(Bmp,sizeof(BITMAP),&bmp);
    int nChannels = bmp.bmBitsPixel == 1 ? 1 : bmp.bmBitsPixel/8 ;
    int depth = bmp.bmBitsPixel == 1 ? IPL_DEPTH_1U : IPL_DEPTH_8U;
    Mat v_mat;
    v_mat.create(cvSize(bmp.bmWidth,bmp.bmHeight), CV_MAKETYPE(CV_8U,nChannels));
    GetBitmapBits(Bmp,bmp.bmHeight*bmp.bmWidth*nChannels,v_mat.data);
    Mat img = v_mat;
    Detect det;
    list<int> matrix = det.get_face_rect(img);
    if(matrix.begin() == matrix.end())
    {
        return false;
    }
    else
    {
        list<int>::iterator iter = matrix.begin();
        int r;
        int size = matrix.size();
        for(r = 0; r < size ; r++){
            if(r == size - 1)
            {
                N[r] = *iter;
            }else{
                N[r] = *iter++;
            }
        }
        return true;
    }
}

 

调用时直接传入一张图的指针,会返回出是否取到脸,然后通过指针获取人脸的x,y,width,height