mfc vs c++ 人脸识别项目

#include <dlib/opencv.h>
#include <opencv2/opencv.hpp>
#include <dlib/image_processing/frontal_face_detector.h>//cv2+dlib库自带frontal_face_detector(人脸征检测器)
#include <dlib/image_processing/render_face_detections.h> #include <dlib/image_processing.h> #include <dlib/gui_widgets.h> #include<windows.h> #include<string> #include<cmath> #include <dlib/gui_widgets.h> #include <dlib/clustering.h> #include <dlib/string.h> #include <dlib/dnn.h> #include <dlib/image_io.h> #include <dlib/image_processing/frontal_face_detector.h> using namespace dlib; using namespace std; //下面是神经网络需要用到的东西 CNN网络 template <template <int, template<typename>class, int, typename> class block, int N, template<typename>class BN, typename SUBNET> using residual = add_prev1<block<N, BN, 1, tag1<SUBNET>>>; template <template <int, template<typename>class, int, typename> class block, int N, template<typename>class BN, typename SUBNET> using residual_down = add_prev2<avg_pool<2, 2, 2, 2, skip1<tag2<block<N, BN, 2, tag1<SUBNET>>>>>>; template <int N, template <typename> class BN, int stride, typename SUBNET> using block = BN<con<N, 3, 3, 1, 1, relu<BN<con<N, 3, 3, stride, stride, SUBNET>>>>>; template <int N, typename SUBNET> using ares = relu<residual<block, N, affine, SUBNET>>; template <int N, typename SUBNET> using ares_down = relu<residual_down<block, N, affine, SUBNET>>; template <typename SUBNET> using alevel0 = ares_down<256, SUBNET>; template <typename SUBNET> using alevel1 = ares<256, ares<256, ares_down<256, SUBNET>>>; template <typename SUBNET> using alevel2 = ares<128, ares<128, ares_down<128, SUBNET>>>; template <typename SUBNET> using alevel3 = ares<64, ares<64, ares<64, ares_down<64, SUBNET>>>>; template <typename SUBNET> using alevel4 = ares<32, ares<32, ares<32, SUBNET>>>; using anet_type = loss_metric<fc_no_bias<128, avg_pool_everything< alevel0< alevel1< alevel2< alevel3< alevel4< max_pool<3, 3, 2, 2, relu<affine<con<32, 7, 7, 2, 2, input_rgb_image_sized<150> >>>>>>>>>>>>; // ---------------------------------------------------------------------------------------- int main() { try { cv::VideoCapture cap(0);//调用摄像头 if (!cap.isOpened()) { cerr << "unable to connect to camera" << endl;//cerr跟cout差不多 但是常用来输出错误信息 return 1; } frontal_face_detector detector = get_frontal_face_detector(); //姿势判断 shape_predictor sp; deserialize("D:/code/vs_dlib/library/shape_predictor_68_face_landmarks.dat") >> sp; // dnn神经网络的应用 anet_type net; deserialize("D:/code/vs_dlib/library/dlib_face_recognition_resnet_model_v1.dat") >> net; int key;//用来处理键盘事件 string name;//用来 保存截屏图片的名字 while (cv::waitKey(30) != 27){ //等于27 的时候是指按下Esc键的时候 key = cv::waitKey(10); //----------------------------------------------------------------------------------------------------------------------------------------------------------- - 摄像头图片 //用mat来存储图像数据 cv::Mat temp; cap >> temp;//将数据传给cap cv_image<bgr_pixel> cimg(temp);//转换成opencv的iamge形式 std::vector<rectangle> faceshh = detector(cimg); // Find the pose of each face. std::vector<full_object_detection> shapes; for (unsigned long i = 0; i < faceshh.size(); ++i) shapes.push_back(sp(cimg, faceshh[i])); std::vector<matrix<rgb_pixel>> faces; //对摄像头图片进行缩放 for (auto face : detector(cimg)) { auto shape = sp(cimg, face); matrix<rgb_pixel> face_chip; //对 shape特征值 以及人脸进行缩放 extract_image_chip(cimg, get_face_chip_details(shape, 150, 0.25), face_chip); faces.push_back(move(face_chip)); } //--------------------------------------------------------------------------------------------------------------------------------------------------- //文件夹中的图片 matrix<rgb_pixel> xxr; load_image(xxr, "D:\code\vs_dlib\face_Recognize\x64\Release\faces\xxr.jpg"); std::vector<matrix<rgb_pixel>> xxr_face; for (auto face : detector(xxr)) { auto shape_xxr = sp(xxr, face); matrix<rgb_pixel> face_chip; //对 shape特征值 以及人脸进行缩放 extract_image_chip(xxr, get_face_chip_details(shape_xxr, 150, 0.25), face_chip); xxr_face.push_back(move(face_chip)); } //----------------------------------------------------------------------------------------------------------------------------------------------------------- //键盘事件的处理 switch (key) { case 's': //执行截图事件 cv::imwrite("D:\code\vs_dlib\face_Recognize\x64\Release\faces\" + name + ".jpg",temp); break; case 'i': //执行输入姓名事件 while (key != '!') { name = name +(char) key; } break; } //--------------------------------------------------------------------------------------------------------------------------------------------------------------- //人脸特征的存储 std::vector<matrix<float, 0, 1>> face_descriptors = net(faces); std::vector<matrix<float, 0, 1>> facexxr_descriptors = net(xxr_face); //人脸识别的判断 for (size_t i = 0; i < face_descriptors.size(); ++i) { for (size_t j = 0; j < facexxr_descriptors.size(); j++){ if (length(face_descriptors[i] - facexxr_descriptors[j]) < 0.6) { //说明这两个人脸是相似的 circle(temp, cvPoint(shapes[i].part(30).x(), shapes[i].part(30).y()), 100, cv::Scalar(0, 0, 255), 1); putText(temp,"xxr",cvPoint(shapes[i].part(30).x(), shapes[i].part(30).y() + 100), CV_FONT_HERSHEY_SIMPLEX, 1, (187, 255, 255), 4.8); }else { circle(temp, cvPoint(shapes[i].part(30).x(), shapes[i].part(30).y()), 100, cv::Scalar(255, 0, 0), 1); putText(temp,"Unknown",cvPoint(shapes[i].part(30).x(), shapes[i].part(30).y() + 100), CV_FONT_HERSHEY_SIMPLEX, 1, (187, 255, 255), 4.8); } } } imshow("Dlib特征点", temp); } } catch (std::exception& e) { cout << e.what() << endl; } }

 好像是添加了MFC界面的代码:

// camera_mfc_test1Dlg.cpp : 实现文件
//
#include "stdafx.h"
#include <opencv2/opencv.hpp>
#include "CvvImage.h"
#include <dlib/opencv.h>
#include <opencv2/opencv.hpp>
#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing/render_face_detections.h>
#include <dlib/image_processing.h>
#include <dlib/gui_widgets.h>
#include<windows.h>
#include<string>
#include<cmath>
#include <dlib/gui_widgets.h>
#include <dlib/clustering.h>
#include <dlib/string.h>
#include <dlib/dnn.h>
#include <dlib/image_io.h>
#include <dlib/image_processing/frontal_face_detector.h>
#include "camera_mfc_test1.h"
#include "camera_mfc_test1Dlg.h"
#include "afxdialogex.h"
using namespace std;  
using namespace dlib;
using namespace cv;



#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#define WM_UPDATE_STATIC (WM_USER + 100)


CvCapture* m_Video;
VideoCapture Capture;
Mat frame; //定义Mat变量,用来存储每一帧 
IplImage frame2;//opencv里面的对图像处理的 像素
IplImage *framecv;
IplImage* m_grabframe;
CRect rect;
CDC *pDC;//CDC中各种绘图函数
HDC hDC;//
CWnd *pwnd;
//放图片的名字
std::vector<cv::String> files; 
//int ImgNum = 0;
bool threadFlag = FALSE;//线程的开关
CWinThread *m_pThread;
CString str_name;
//下面是神经网络需要用到的东西  CNN网络
template <template <int, template<typename>class, int, typename> class block, int N, template<typename>class BN, typename SUBNET>
using residual = add_prev1<block<N, BN, 1, tag1<SUBNET>>>;

template <template <int, template<typename>class, int, typename> class block, int N, template<typename>class BN, typename SUBNET>
using residual_down = add_prev2<avg_pool<2, 2, 2, 2, skip1<tag2<block<N, BN, 2, tag1<SUBNET>>>>>>;

template <int N, template <typename> class BN, int stride, typename SUBNET>
using block = BN<con<N, 3, 3, 1, 1, relu<BN<con<N, 3, 3, stride, stride, SUBNET>>>>>;

template <int N, typename SUBNET> using ares = relu<residual<block, N, affine, SUBNET>>;
template <int N, typename SUBNET> using ares_down = relu<residual_down<block, N, affine, SUBNET>>;

template <typename SUBNET> using alevel0 = ares_down<256, SUBNET>;
template <typename SUBNET> using alevel1 = ares<256, ares<256, ares_down<256, SUBNET>>>;
template <typename SUBNET> using alevel2 = ares<128, ares<128, ares_down<128, SUBNET>>>;
template <typename SUBNET> using alevel3 = ares<64, ares<64, ares<64, ares_down<64, SUBNET>>>>;
template <typename SUBNET> using alevel4 = ares<32, ares<32, ares<32, SUBNET>>>;

using anet_type = loss_metric<fc_no_bias<128, avg_pool_everything<
    alevel0<
    alevel1<
    alevel2<
    alevel3<
    alevel4<
    max_pool<3, 3, 2, 2, relu<affine<con<32, 7, 7, 2, 2,
    input_rgb_image_sized<150>
    >>>>>>>>>>>>;







// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
    CAboutDlg();

// 对话框数据
#ifdef AFX_DESIGN_TIME
    enum { IDD = IDD_ABOUTBOX };
#endif

    protected:
    virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
    DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// Ccamera_mfc_test1Dlg 对话框



Ccamera_mfc_test1Dlg::Ccamera_mfc_test1Dlg(CWnd* pParent /*=NULL*/)
    : CDialogEx(IDD_CAMERA_MFC_TEST1_DIALOG, pParent)
{
    m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void Ccamera_mfc_test1Dlg::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(Ccamera_mfc_test1Dlg, CDialogEx)
    ON_WM_SYSCOMMAND()
    ON_WM_PAINT()
    ON_WM_QUERYDRAGICON()

    ON_MESSAGE(WM_UPDATE_STATIC, &Ccamera_mfc_test1Dlg::OnUpdateStatic)
    ON_BN_CLICKED(open, &Ccamera_mfc_test1Dlg::On_OpenCamera)
    ON_WM_TIMER()
    ON_BN_CLICKED(close, &Ccamera_mfc_test1Dlg::On_CloseCamera)
    ON_BN_CLICKED(get_pic, &Ccamera_mfc_test1Dlg::On_CaptureImage)
END_MESSAGE_MAP()


// Ccamera_mfc_test1Dlg 消息处理程序

BOOL Ccamera_mfc_test1Dlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();
    

    // 将“关于...”菜单项添加到系统菜单中。

    // IDM_ABOUTBOX 必须在系统命令范围内。
    ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
    ASSERT(IDM_ABOUTBOX < 0xF000);

    CMenu* pSysMenu = GetSystemMenu(FALSE);
    if (pSysMenu != NULL)
    {
        BOOL bNameValid;
        CString strAboutMenu;
        bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
        ASSERT(bNameValid);
        if (!strAboutMenu.IsEmpty())
        {
            pSysMenu->AppendMenu(MF_SEPARATOR);
            pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
        }
    }

    // 设置此对话框的图标。  当应用程序主窗口不是对话框时,框架将自动
    //  执行此操作
    SetIcon(m_hIcon, TRUE);            // 设置大图标
    SetIcon(m_hIcon, FALSE);        // 设置小图标

    // TODO: 在此添加额外的初始化代码

    return TRUE;  // 除非将焦点设置到控件,否则返回 TRUE
}

void Ccamera_mfc_test1Dlg::OnSysCommand(UINT nID, LPARAM lParam)
{
    if ((nID & 0xFFF0) == IDM_ABOUTBOX)
    {
        CAboutDlg dlgAbout;
        dlgAbout.DoModal();
    }
    else
    {
        CDialogEx::OnSysCommand(nID, lParam);
    }
}

// 如果向对话框添加最小化按钮,则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序,
//  这将由框架自动完成。

void Ccamera_mfc_test1Dlg::OnPaint()
{
    if (IsIconic())
    {
        CPaintDC dc(this); // 用于绘制的设备上下文

        SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

        // 使图标在工作区矩形中居中
        int cxIcon = GetSystemMetrics(SM_CXICON);
        int cyIcon = GetSystemMetrics(SM_CYICON);
        CRect rect;
        GetClientRect(&rect);
        int x = (rect.Width() - cxIcon + 1) / 2;
        int y = (rect.Height() - cyIcon + 1) / 2;

        // 绘制图标
        dc.DrawIcon(x, y, m_hIcon);
    }
    else
    {
        CDialogEx::OnPaint();
    }
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR Ccamera_mfc_test1Dlg::OnQueryDragIcon()
{
    return static_cast<HCURSOR>(m_hIcon);
}

//多线程实现 视频的播放
LRESULT Ccamera_mfc_test1Dlg::OnUpdateStatic(WPARAM wParam, LPARAM lParam)
{
    
        //GetDlgItem(IDC_STATIC)->SetWindowText(L"Hello Linux");
        pDC = GetDlgItem(IDC_PIC_STATIC)->GetDC();//GetDlgItem(IDC_PIC_STATIC)意思为获取显示控件的句柄(句柄就是指针),获取显示控件的DC
        GetDlgItem(IDC_PIC_STATIC)->GetClientRect(&rect);
        hDC = pDC->GetSafeHdc();//获取显示控件的句柄
        CvvImage m_CvvImage;
        m_CvvImage.CopyOf(framecv, 1); //复制该帧图像   
        m_CvvImage.DrawToHDC(hDC, &rect); //显示到设备的矩形框内
        cvWaitKey(25);
    return 0;
}


 UINT Ccamera_mfc_test1Dlg::ThreadFunction(LPVOID pParam)
{
    Ccamera_mfc_test1Dlg *pDlg = (Ccamera_mfc_test1Dlg *)pParam;
    cv::VideoCapture  Capture(0);//调用摄像头
    frontal_face_detector detector = get_frontal_face_detector();
        //姿势判断
        shape_predictor sp; 
            deserialize("D:/code/vs_dlib/library/shape_predictor_68_face_landmarks.dat") >> sp;
        // dnn神经网络的应用
        anet_type net;
        deserialize("D:/code/vs_dlib/library/dlib_face_recognition_resnet_model_v1.dat") >> net;

        
    if (!Capture.isOpened())
    {
        pDlg->MessageBox(_T("无法连接摄像头!!!"));
        return 0;
    }

    while (Capture.isOpened()) {
        Capture >> frame;//读取当前帧方法一
        
        
            

            cv_image<bgr_pixel> cimg(frame);//转换成opencv的iamge形式

            std::vector<dlib::rectangle> faceshh = detector(cimg);

            // Find the pose of each face.
            std::vector<full_object_detection> shapes;
            for (unsigned long i = 0; i < faceshh.size(); ++i)
                shapes.push_back(sp(cimg, faceshh[i]));
            std::vector<matrix<rgb_pixel>> faces;
            
            //对摄像头图片进行缩放
            for (auto face : detector(cimg))
            {
                auto  shape = sp(cimg, face);
                matrix<rgb_pixel> face_chip;
                //对 shape特征值 以及人脸进行缩放
                extract_image_chip(cimg, get_face_chip_details(shape, 150, 0.25), face_chip);
                faces.push_back(move(face_chip));



            }


//---------------------------------------------------------------------------------------------------------------------------------------------------
            //文件夹中的图片

            matrix<rgb_pixel> xxr;
            Mat img;
            string files_path = "C:/Users/xxr/Pictures/Saved Pictures/*.jpg";
            
            glob( files_path, files, false);
            size_t count = files.size(); 
            for (int i = 0; i < count; i++) {
                img.push_back(imread(files[i]));
                


                array2d< bgr_pixel> arrimg(img.rows, img.cols);
                dlib::assign_image(xxr, cv_image<rgb_pixel>(img));

            }



            //load_image(xxr, "D:\code\vs_dlib\face_Recognize\x64\Release\faces\xxr.jpg");











            std::vector<matrix<rgb_pixel>> xxr_face;
            for (auto face : detector(xxr))
            {
                auto shape_xxr = sp(xxr, face);
                matrix<rgb_pixel> face_chip;
                //对 shape特征值 以及人脸进行缩放
                extract_image_chip(xxr, get_face_chip_details(shape_xxr, 150, 0.25), face_chip);
                xxr_face.push_back(move(face_chip));



            }

            //人脸特征的存储
            std::vector<matrix<float, 0, 1>> face_descriptors = net(faces);
            std::vector<matrix<float, 0, 1>> facexxr_descriptors = net(xxr_face);


            

            for (size_t i = 0; i < face_descriptors.size(); ++i)
            {//人脸识别的判断
            bool flag = false;
                for (size_t j = 0; j < facexxr_descriptors.size(); j++){
                    if (length(face_descriptors[i] - facexxr_descriptors[j]) < 0.6) {
                    //说明这两个人脸是相似的

                    circle(frame, cvPoint(shapes[i].part(30).x(), shapes[i].part(30).y()), 100, cv::Scalar(0, 0, 255), 1);
                    std::string hh = files[j-1];
                    putText(frame,hh.erase(0, 37) ,cvPoint(shapes[i].part(30).x(), shapes[i].part(30).y() + 100), CV_FONT_HERSHEY_SIMPLEX, 1, (187, 255, 255), 4.8);
                    flag = true;
                    }

                }
                if (!flag) {
                
                    circle(frame, cvPoint(shapes[i].part(30).x(), shapes[i].part(30).y()), 100, cv::Scalar(255, 0, 0), 1);
                    putText(frame,"Unknown",cvPoint(shapes[i].part(30).x(), shapes[i].part(30).y() + 100), CV_FONT_HERSHEY_SIMPLEX, 1, (187, 255, 255), 4.8);
                    
            }

        }
            
        frame2 = frame;
        framecv = cvCloneImage(&frame2);
        ::PostMessage(pDlg->m_hWnd, WM_UPDATE_STATIC, 0, 0);
            //imshow("Dlib特征点", temp);


    }
    return 0;
}


void Ccamera_mfc_test1Dlg::On_OpenCamera()
{
//    MessageBox(_T("dakai摄像头!!!"));
    m_pThread = AfxBeginThread((AFX_THREADPROC)ThreadFunction, this); 
}
    
    







void Ccamera_mfc_test1Dlg::On_CloseCamera()
{
    // TODO: 在此添加控件通知处理程序代码
    // TODO: Add your command handler code here
    if (!Capture.isOpened())
    {
        MessageBox(_T("没有打开摄像头!!!"));
        return;
    }
    
    Capture.release();
 
    pDC = GetDlgItem(IDC_PIC_STATIC)->GetDC();//GetDlgItem(IDC_PIC_STATIC)意思为获取显示控件的句柄(句柄就是指针),获取显示控件的DC
 
    GetDlgItem(IDC_PIC_STATIC)->GetClientRect(&rect);
 
    hDC = pDC->GetSafeHdc();//获取显示控件的句柄
 
    framecv = cvLoadImage("C:\Users\xxr\Pictures\Saved Pictures\hh.jpg"); //图片读取路径可以自己设定
    CvvImage m_CvvImage;
    m_CvvImage.CopyOf(framecv, 1); //复制该帧图像   
    m_CvvImage.DrawToHDC(hDC, &rect); //显示到设备的矩形框内
    ReleaseDC(pDC);


}


void Ccamera_mfc_test1Dlg::On_CaptureImage()
{
    CEdit *edit_name;
    edit_name=(CEdit*)GetDlgItem(edit_namehh);
    edit_name-> GetWindowText(str_name);

   
    // TODO: 在此添加控件通知处理程序代码
    m_grabframe = framecv;
    if (m_grabframe == 0)
    {
        MessageBox(_T("摄像头已关闭,无法捕捉图像!!!"));
        return;
    }
    
    CString ImagePath=TEXT("C:\Users\xxr\Pictures\Saved Pictures\");
 
    //CString ImagePath = _T("D:\Documents\Visual Studio 2013\Projects\标定图片\");
 
    if (!PathIsDirectory(ImagePath))
 
    {
        CreateDirectory(ImagePath, 0);//不存在则创建
        MessageBox(_T("标定图片文件夹已创建!!!"));
        return;
    }
    char ImagesName[100];
 
    //ImgNum = ImgNum + 1;
    std::string str( CW2A( str_name.GetString() ) );  
 
    sprintf_s(ImagesName, "%s%s%s", "C:\Users\xxr\Pictures\Saved Pictures\", str, ".jpg");
    
    IplImage * m_snap = cvCreateImage(cvGetSize(m_grabframe), m_grabframe->depth, m_grabframe->nChannels);
    cvCopy(m_grabframe, m_snap, NULL);
    cvSaveImage(ImagesName, m_snap); //把图像写入指定文件夹的文件中去
 
    //以下代码是完成图像的显示过程
    pDC = GetDlgItem(IDC_PIC1_STATIC)->GetDC();//GetDlgItem(IDC_PIC_STATIC)意思为获取显示控件的句柄(句柄就是指针),获取显示控件的DC
 
    GetDlgItem(IDC_PIC1_STATIC)->GetClientRect(&rect);
 
    hDC = pDC->GetSafeHdc();//获取显示控件的句柄
 
    CvvImage m_CvvImage;
    m_CvvImage.CopyOf(m_snap, 1); //复制该帧图像   
    m_CvvImage.DrawToHDC(hDC, &rect); //显示到设备环境的矩形框内

}

连接数据库

#include <dlib/opencv.h>
#include <opencv2/opencv.hpp>
#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing/render_face_detections.h>
#include <dlib/image_processing.h>
#include <dlib/gui_widgets.h>
#include<windows.h>
#include<string>
#include<cmath>
#include <dlib/gui_widgets.h>
#include <dlib/clustering.h>
#include <dlib/string.h>
#include <dlib/dnn.h>
#include <dlib/image_io.h>
#include <dlib/image_processing/frontal_face_detector.h>

#include <winsock.h>
#include <iostream>
#include <string>
#include <mysql.h>

//单步执行,不想单步执行就注释掉
#define STEPBYSTEP


using namespace dlib;
using namespace std;
//下面是神经网络需要用到的东西  CNN网络
template <template <int, template<typename>class, int, typename> class block, int N, template<typename>class BN, typename SUBNET>
using residual = add_prev1<block<N, BN, 1, tag1<SUBNET>>>;

template <template <int, template<typename>class, int, typename> class block, int N, template<typename>class BN, typename SUBNET>
using residual_down = add_prev2<avg_pool<2, 2, 2, 2, skip1<tag2<block<N, BN, 2, tag1<SUBNET>>>>>>;

template <int N, template <typename> class BN, int stride, typename SUBNET>
using block = BN<con<N, 3, 3, 1, 1, relu<BN<con<N, 3, 3, stride, stride, SUBNET>>>>>;

template <int N, typename SUBNET> using ares = relu<residual<block, N, affine, SUBNET>>;
template <int N, typename SUBNET> using ares_down = relu<residual_down<block, N, affine, SUBNET>>;

template <typename SUBNET> using alevel0 = ares_down<256, SUBNET>;
template <typename SUBNET> using alevel1 = ares<256, ares<256, ares_down<256, SUBNET>>>;
template <typename SUBNET> using alevel2 = ares<128, ares<128, ares_down<128, SUBNET>>>;
template <typename SUBNET> using alevel3 = ares<64, ares<64, ares<64, ares_down<64, SUBNET>>>>;
template <typename SUBNET> using alevel4 = ares<32, ares<32, ares<32, SUBNET>>>;

using anet_type = loss_metric<fc_no_bias<128, avg_pool_everything<
    alevel0<
    alevel1<
    alevel2<
    alevel3<
    alevel4<
    max_pool<3, 3, 2, 2, relu<affine<con<32, 7, 7, 2, 2,
    input_rgb_image_sized<150>
    >>>>>>>>>>>>;

// ----------------------------------------------------------------------------------------



int main() {
    try
    {   
        //必备的一个数据结构
    MYSQL mydata;

    //初始化数据库
    if (0 == mysql_library_init(0, NULL, NULL)) {
        cout << "mysql_library_init() succeed" << endl;
    }
    else {
        cout << "mysql_library_init() failed" << endl;
        return -1;
    }

    //初始化数据结构
    if (NULL != mysql_init(&mydata)) {
        cout << "mysql_init() succeed" << endl;
    }
    else {
        cout << "mysql_init() failed" << endl;
        return -1;
    }
    //在连接数据库之前,设置额外的连接选项
    //可以设置的选项很多,这里设置字符集,否则无法处理中文
    if (0 == mysql_options(&mydata, MYSQL_SET_CHARSET_NAME, "gbk")) {
        cout << "mysql_options() succeed" << endl;
    }
    else {
        cout << "mysql_options() failed" << endl;
        return -1;
    }
    

    //连接数据库
    if (NULL
        != mysql_real_connect(&mydata, "localhost", "root", "19990209", "test",3306, NULL, 0))
        //这里的地址,用户名,密码,端口可以根据自己本地的情况更改
    {
        cout << "mysql_real_connect() succeed" << endl;
    }
    else {
        cout << "mysql_real_connect() failed" << endl;
        return -1;
    }
    
    //sql字符串
    string sqlstr;

    //创建一个表
    sqlstr = "CREATE TABLE IF NOT EXISTS face_dect";
    sqlstr += "(";
    sqlstr +=
        "user_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique User ID',";
    sqlstr +=
        "user_name VARCHAR(100) CHARACTER SET gb2312 COLLATE gb2312_chinese_ci NULL COMMENT 'Name Of User',";
    sqlstr +=
        "user_fece VARCHAR(60000) "; 

    sqlstr += ");";
    if (0 == mysql_query(&mydata, sqlstr.c_str())) {
        cout << "mysql_query() create table succeed" << endl;
    }
    else {
        cout << "mysql_query() create table failed" << endl;
        mysql_close(&mydata);
        return -1;
    }

        cv::VideoCapture  cap(0);//调用摄像头
        if (!cap.isOpened()) {
            cerr << "unable to connect to camera" << endl;//cerr跟cout差不多 但是常用来输出错误信息
            return 1;
        }
        frontal_face_detector detector = get_frontal_face_detector();
        //姿势判断
        shape_predictor sp; 
            deserialize("D:/code/vs_dlib/library/shape_predictor_68_face_landmarks.dat") >> sp;
        // dnn神经网络的应用
        anet_type net;
        deserialize("D:/code/vs_dlib/library/dlib_face_recognition_resnet_model_v1.dat") >> net;

        int key;//用来处理键盘事件
        string name;//用来 保存截屏图片的名字

        while (cv::waitKey(30) != 27){ 
            //等于27 的时候是指按下Esc键的时候 
            key = cv::waitKey(10);
        
//-----------------------------------------------------------------------------------------------------------------------------------------------------------    - 摄像头图片
          //用mat来存储图像数据
            cv::Mat temp;
            cap >> temp;//将数据传给cap

            cv_image<bgr_pixel> cimg(temp);//转换成opencv的iamge形式

            std::vector<rectangle> faceshh = detector(cimg);

            // Find the pose of each face.
            std::vector<full_object_detection> shapes;
            for (unsigned long i = 0; i < faceshh.size(); ++i)
                shapes.push_back(sp(cimg, faceshh[i]));
            std::vector<matrix<rgb_pixel>> faces;
            
            //对摄像头图片进行缩放
            for (auto face : detector(cimg))
            {
                auto  shape = sp(cimg, face);
                matrix<rgb_pixel> face_chip;
                //对 shape特征值 以及人脸进行缩放
                extract_image_chip(cimg, get_face_chip_details(shape, 150, 0.25), face_chip);
                faces.push_back(move(face_chip));



            }






//---------------------------------------------------------------------------------------------------------------------------------------------------
            //文件夹中的图片

            matrix<rgb_pixel> xxr;
            load_image(xxr, "D:\code\vs_dlib\face_Recognize\x64\Release\faces\xxr.jpg");
            std::vector<matrix<rgb_pixel>> xxr_face;
            for (auto face : detector(xxr))
            {
                auto shape_xxr = sp(xxr, face);
                matrix<rgb_pixel> face_chip;
                //对 shape特征值 以及人脸进行缩放
                extract_image_chip(xxr, get_face_chip_details(shape_xxr, 150, 0.25), face_chip);
                xxr_face.push_back(move(face_chip));



            }
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
            //键盘事件的处理

            switch (key) {
        case 's':
            //执行截图事件
            cv::imwrite("D:\code\vs_dlib\face_Recognize\x64\Release\faces\" + name + ".jpg",temp);
            break;
        case 'i':
            //执行输入姓名事件
            while (key != '!') {
                name = name +(char) key;

            }

            break;
        
            }







//---------------------------------------------------------------------------------------------------------------------------------------------------------------
    
            //人脸特征的存储
            std::vector<matrix<float, 0, 1>> face_descriptors = net(faces);
            std::vector<matrix<float, 0, 1>> facexxr_descriptors = net(xxr_face);

            
    string str;
    bool flag = true;
    if (true) {
        for (int i = 0; i < facexxr_descriptors.size(); i++) {
                for (long r = 0; r < facexxr_descriptors[i].nr(); r++) {

                    for (long c = 0; c < facexxr_descriptors[i].nc(); ++c) {
                        
                        cout << ""<<i<<""<< "" << r << "" << "" << c << "";
                        cout << facexxr_descriptors[i](r, c)<<endl;
                        str = facexxr_descriptors[i](r, c) ;
                        str = str + "&";
                    }
                }
                //向表中插入数据

    sqlstr =
        "INSERT INTO face_dect(user_name,user_face) VALUES('xxr',str);";
    if (0 == mysql_query(&mydata, sqlstr.c_str())) {
        cout << "mysql_query() insert data succeed" << endl;
    }
    else {
        cout << "mysql_query() insert data failed" << endl;
        mysql_close(&mydata);
        return -1;
    }
            }
        flag = false;
        
    }

            



        //    printf(face_descriptors);
            //人脸识别的判断

            for (size_t i = 0; i < face_descriptors.size(); ++i)
            {
                for (size_t j = 0; j < facexxr_descriptors.size(); j++){
                    if (length(face_descriptors[i] - facexxr_descriptors[j]) < 0.6) {
                    //说明这两个人脸是相似的

                    circle(temp, cvPoint(shapes[i].part(30).x(), shapes[i].part(30).y()), 100, cv::Scalar(0, 0, 255), 1);
                    putText(temp,"xxr",cvPoint(shapes[i].part(30).x(), shapes[i].part(30).y() + 100), CV_FONT_HERSHEY_SIMPLEX, 1, (187, 255, 255), 4.8);
                    }else {
                        circle(temp, cvPoint(shapes[i].part(30).x(), shapes[i].part(30).y()), 100, cv::Scalar(255, 0, 0), 1);
                    putText(temp,"Unknown",cvPoint(shapes[i].part(30).x(), shapes[i].part(30).y() + 100), CV_FONT_HERSHEY_SIMPLEX, 1, (187, 255, 255), 4.8);
                    }
                }

        }
            imshow("Dlib特征点", temp);

        }
    }
    catch (std::exception& e)
    {
        cout << e.what() << endl;
    }

}
原文地址:https://www.cnblogs.com/kekexxr/p/12290413.html