(C++)人脸识别
phpskycn2010/02/12软件综合 IP:浙江
=====================版权声明=======================
此代码来自电子工业出版社的《数字图象处理开发》一书所附光盘,
版权归原作者 左飞 万晋森 刘航 所有。
未经原作者允许,请勿用于商业用途,否则后果自负!
===================================================
*请使用Visual C++ 2005或以上版本,对BCB兼容性未测试
完整源代码下载:

attachment icon 第15章.rar 1.52MB RAR 30次下载


// FaceDetection.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "FaceDetection.h"
#include "FaceDetectionDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CFaceDetectionApp

BEGIN_MESSAGE_MAP(CFaceDetectionApp, CWinApp)
    ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()


// CFaceDetectionApp construction

CFaceDetectionApp::CFaceDetectionApp()
{
    // TODO: add construction code here,
    // Place all significant initialization in InitInstance
}


// The one and only CFaceDetectionApp object

CFaceDetectionApp theApp;


// CFaceDetectionApp initialization

BOOL CFaceDetectionApp::InitInstance()
{
    // InitCommonControlsEx() is required on Windows XP if an application
    // manifest specifies use of ComCtl32.dll version 6 or later to enable
    // visual styles.  Otherwise, any window creation will fail.
    INITCOMMONCONTROLSEX InitCtrls;
    InitCtrls.dwSize = sizeof(InitCtrls);
    // Set this to include all the common control classes you want to use
    // in your application.
    InitCtrls.dwICC = ICC_WIN95_CLASSES;
    InitCommonControlsEx(&InitCtrls);

    CWinApp::InitInstance();

    AfxEnableControlContainer();

    // Standard initialization
    // If you are not using these features and wish to reduce the size
    // of your final executable, you should remove from the following
    // the specific initialization routines you do not need
    // Change the registry key under which our settings are stored
    // TODO: You should modify this string to be something appropriate
    // such as the name of your company or organization
    SetRegistryKey(_T("Local AppWizard-Generated Applications"));

    CFaceDetectionDlg dlg;
    m_pMainWnd = &dlg;
    INT_PTR nResponse = XXXXXXModal();
    if (nResponse == IDOK)
    {
        // TODO: Place code here to handle when the dialog is
        //  dismissed with OK
    }
    else if (nResponse == IDCANCEL)
    {
        // TODO: Place code here to handle when the dialog is
        //  dismissed with Cancel
    }

    // Since the dialog has been closed, return FALSE so that we exit the
    //  application, rather than start the application's message pump.
    return FALSE;
}
// FaceDetectionDlg.h : header file
//

#pragma once

#include "cv.h"
#include "highgui.h"

// CFaceDetectionDlg dialog
class CFaceDetectionDlg : public CDialog
{
// Construction
public:
    CFaceDetectionDlg(CWnd* pParent = NULL);    // standard constructor

    CvHaarClassifierCascade* cascade;
    CvMemStorage* storage;
    void detect_and_draw( IplImage* img );

    IplImage* src;
    //CString cascade_name;

// Dialog Data
    enum { IDD = IDD_FACEDETECTION_DIALOG };

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


// Implementation
protected:
    HICON m_hIcon;

    // Generated message map functions
    virtual BOOL OnInitDialog();
    afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
    afx_msg void OnPaint();
    afx_msg HCURSOR OnQueryDragIcon();
    DECLARE_MESSAGE_MAP()
public:
    afx_msg void OnBnClickedOk();
public:
    afx_msg void OnDestroy();
};
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by FaceDetection.RC
//
#define IDR_MAINFRAME                    128
#define IDM_ABOUTBOX                    0x0010
#define IDD_ABOUTBOX                    100
#define IDS_ABOUTBOX                    101
#define IDD_FACEDETECTION_DIALOG                102

// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS

#define _APS_NEXT_RESOURCE_VALUE    129
#define _APS_NEXT_CONTROL_VALUE        1000
#define _APS_NEXT_SYMED_VALUE        101
#define _APS_NEXT_COMMAND_VALUE        32771
#endif
#endif
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently,
// but are changed infrequently

#pragma once

#ifndef _SECURE_ATL
#define _SECURE_ATL 1
#endif

#ifndef VC_EXTRALEAN
#define VC_EXTRALEAN        // Exclude rarely-used stuff from Windows headers
#endif

// Modify the following defines if you have to target a platform prior to the ones specified below.
// Refer to MSDN for the latest info on corresponding values for different platforms.
#ifndef WINVER                // Allow use of features specific to Windows XP or later.
#define WINVER 0x0501        // Change this to the appropriate value to target other versions of Windows.
#endif

#ifndef _WIN32_WINNT        // Allow use of features specific to Windows XP or later.                  
#define _WIN32_WINNT 0x0501    // Change this to the appropriate value to target other versions of Windows.
#endif                        

#ifndef _WIN32_WINDOWS        // Allow use of features specific to Windows 98 or later.
#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later.
#endif

#ifndef _WIN32_IE            // Allow use of features specific to IE 6.0 or later.
#define _WIN32_IE 0x0600    // Change this to the appropriate value to target other versions of IE.
#endif

#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS    // some CString constructors will be explicit

// turns off MFC's hiding of some common and often safely ignored warning messages
#define _AFX_ALL_WARNINGS

#include <afxwin.h>         // MFC core and standard components
#include <afxext.h>         // MFC extensions


#include <afxdisp.h>        // MFC Automation classes



#ifndef _AFX_NO_OLE_SUPPORT
#include <afxdtctl.h>        // MFC support for Internet Explorer 4 Common Controls
#endif
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h>            // MFC support for Windows Common Controls
#endif // _AFX_NO_AFXCMN_SUPPORT









#ifdef _UNICODE
#if defined _M_IX86
#pragma comment(linker,"/manifestdependency:\"type='win32' name='XXXXXXXXXXXXXXXXXXXXXmon-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_IA64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='XXXXXXXXXXXXXXXXXXXXXmon-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_X64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='XXXXXXXXXXXXXXXXXXXXXmon-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#else
#pragma comment(linker,"/manifestdependency:\"type='win32' name='XXXXXXXXXXXXXXXXXXXXXmon-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
#endif


// FaceDetection.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "FaceDetection.h"
#include "FaceDetectionDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CFaceDetectionApp

BEGIN_MESSAGE_MAP(CFaceDetectionApp, CWinApp)
    ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()


// CFaceDetectionApp construction

CFaceDetectionApp::CFaceDetectionApp()
{
    // TODO: add construction code here,
    // Place all significant initialization in InitInstance
}


// The one and only CFaceDetectionApp object

CFaceDetectionApp theApp;


// CFaceDetectionApp initialization

BOOL CFaceDetectionApp::InitInstance()
{
    // InitCommonControlsEx() is required on Windows XP if an application
    // manifest specifies use of ComCtl32.dll version 6 or later to enable
    // visual styles.  Otherwise, any window creation will fail.
    INITCOMMONCONTROLSEX InitCtrls;
    InitCtrls.dwSize = sizeof(InitCtrls);
    // Set this to include all the common control classes you want to use
    // in your application.
    InitCtrls.dwICC = ICC_WIN95_CLASSES;
    InitCommonControlsEx(&InitCtrls);

    CWinApp::InitInstance();

    AfxEnableControlContainer();

    // Standard initialization
    // If you are not using these features and wish to reduce the size
    // of your final executable, you should remove from the following
    // the specific initialization routines you do not need
    // Change the registry key under which our settings are stored
    // TODO: You should modify this string to be something appropriate
    // such as the name of your company or organization
    SetRegistryKey(_T("Local AppWizard-Generated Applications"));

    CFaceDetectionDlg dlg;
    m_pMainWnd = &dlg;
    INT_PTR nResponse = XXXXXXModal();
    if (nResponse == IDOK)
    {
        // TODO: Place code here to handle when the dialog is
        //  dismissed with OK
    }
    else if (nResponse == IDCANCEL)
    {
        // TODO: Place code here to handle when the dialog is
        //  dismissed with Cancel
    }

    // Since the dialog has been closed, return FALSE so that we exit the
    //  application, rather than start the application's message pump.
    return FALSE;
}
// FaceDetectionDlg.cpp : implementation file
//

#include "stdafx.h"
#include "FaceDetection.h"
#include "FaceDetectionDlg.h"
#include <string>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif

const char* cascade_name =
    "haarcascade_frontalface_alt.xml";

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

// Dialog Data
    enum { IDD = IDD_ABOUTBOX };

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

// Implementation
protected:
    DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg:[s:3]oDataExchange(CDataExchange* pDX)
{
    CDialog:[s:3]oDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


CFaceDetectionDlg::CFaceDetectionDlg(CWnd* pParent /*=NULL*/)
    : CDialog(CFaceDetectionDlg::IDD, pParent)
{
    m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CFaceDetectionDlg:[s:3]oDataExchange(CDataExchange* pDX)
{
    CDialog:[s:3]oDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CFaceDetectionDlg, CDialog)
    ON_WM_SYSCOMMAND()
    ON_WM_PAINT()
    ON_WM_QUERYDRAGICON()
    //}}AFX_MSG_MAP
    ON_BN_CLICKED(IDOK, &CFaceDetectionDlg::OnBnClickedOk)
    ON_WM_DESTROY()
END_MESSAGE_MAP()


// CFaceDetectionDlg message handlers

BOOL CFaceDetectionDlg::OnInitDialog()
{
    CDialog::OnInitDialog();

    // Add "About..." menu item to system menu.

    // IDM_ABOUTBOX must be in the system command range.
    ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
    ASSERT(IDM_ABOUTBOX < 0xF000);

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

    SetIcon(m_hIcon, TRUE);            // Set big icon
    SetIcon(m_hIcon, FALSE);        // Set small icon


    return TRUE;
}

void CFaceDetectionDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
    if ((nID & 0xFFF0) == IDM_ABOUTBOX)
    {
        CAboutDlg dlgAbout;
        XXXXXXXXXXXModal();
    }
    else
    {
        CDialog::OnSysCommand(nID, lParam);
    }
}

void CFaceDetectionDlg::OnPaint()
{
    if (IsIconic())
    {
        CPaintDC dc(this); // device context for painting

        SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(XXXXXtSafeHdc()), 0);

        // Center icon in client rectangle
        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;

        // Draw the icon
        dc.DrawIcon(x, y, m_hIcon);
    }
    else
    {
        CDialog::OnPaint();
    }
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CFaceDetectionDlg::OnQueryDragIcon()
{
    return static_cast<HCURSOR>(m_hIcon);
}


void CFaceDetectionDlg::OnBnClickedOk()
{
    CString fileName;

    //打开文件对话窗口
    CFileDialog OpenDlg( TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR, L"图像文件格式(*.bmp) |*.bmp|JPG file format (*.jpg)|*.jpg|", NULL);

    //从文件对话窗口中打开图像
    if(XXXXXXXXXXModal()!=IDOK)
    return;
    //获得文件名
    fileName = XXXXXXXXXXtPathName();
    //必要的类型转换
    std::string tempName = (LPCSTR)CStringA(fileName);
    const char* tmp = tempName.c_str();

    //打开文件
    //若失败则返回
    if( (src = cvLoadImage(tmp, CV_LOAD_IMAGE_ANYCOLOR)) == 0 )
    return;

    //加载(分类器层叠)训练库
    cascade = (CvHaarClassifierCascade*)cvLoad( cascade_name, 0, 0, 0 );
    
    //加载不成功则显示错误讯息,并退出
    if(cascade)
    {
        storage = cvCreateMemStorage(0);

        cvNamedWindow( "人脸检测", 1 );

        //如果图片存在则分析并显示结果,否则退出程序
        
        if(src) detect_and_draw(src);
        cvReleaseImage(&src);
        cvReleaseMemStorage( &storage );
    }
    else
    {
        AfxMessageBox(L"无法加载分类器,请确认后重试!");
    }
    cvReleaseHaarClassifierCascade( &cascade );
}

void CFaceDetectionDlg::OnDestroy()
{
    CDialog::OnDestroy();
    
    cvDestroyAllWindows();
}


void CFaceDetectionDlg::detect_and_draw(IplImage *img)
{
    //用于图像中多处人脸分离的色彩数组
    static CvScalar colors[] =
    {
        {{0,0,255}},
        {{0,128,255}},
        {{0,255,255}},
        {{0,255,0}},
        {{255,128,0}},
        {{255,255,0}},
        {{255,0,0}},
        {{255,0,255}}
    };

    double scale = 1.3;
    IplImage* gray = cvCreateImage( cvSize(img->width,img->height), 8, 1 );
    IplImage* small_img = cvCreateImage( cvSize( cvRound (img->width/scale),
                         cvRound (img->height/scale)),
                     8, 1 );
    int i;

    cvCvtColor( img, gray, CV_BGR2GRAY );
    cvResize( gray, small_img, CV_INTER_LINEAR );
    cvEqualizeHist( small_img, small_img );
    cvClearMemStorage( storage );

    if( cascade )
    {
        //检测人脸
        CvSeq* faces = cvHaarDetectObjects( small_img, cascade, storage,
                                            1.1, 2, 0/*CV_HAAR_DO_CANNY_PRUNING*/,
                                            cvSize(30, 30) );  

        for( i = 0; i < (faces ? faces->total : 0); i++ )
        {
            CvRect* r = (CvRect*)cvGetSeqElem( faces, i );
            CvPoint center;
            int radius;
            center.x = cvRound((r->x + r->width*0.5)*scale);
            center.y = cvRound((r->y + r->height*0.5)*scale);
            radius = cvRound((r->width + r->height)*0.25*scale);
            cvCircle( img, center, radius, colors[i%8], 3, 8, 0 );
        }
    }

    cvShowImage( "人脸检测", img );
    cvReleaseImage( &gray );
    cvReleaseImage( &small_img );
}
// stdafx.cpp : source file that includes just the standard includes
// FaceDetection.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"
来自:计算机科学 / 软件综合
28
已屏蔽 原因:{{ notice.reason }}已屏蔽
{{notice.noticeContent}}
~~空空如也
phpskycn 作者
14年11个月前 IP:未同步
189261
可能用到OPENCV库
建议直接下包
引用
评论
加载评论中,请稍候...
200字以内,仅用于支线交流,主线讨论请采用回复功能。
折叠评论
phpskycn作者
14年11个月前 IP:未同步
189593
啥结果?
发来看看
引用
评论
加载评论中,请稍候...
200字以内,仅用于支线交流,主线讨论请采用回复功能。
折叠评论
phpskycn作者
14年11个月前 IP:未同步
189710
识别到哪里去了……
引用
评论
加载评论中,请稍候...
200字以内,仅用于支线交流,主线讨论请采用回复功能。
折叠评论
phpskycn作者
14年11个月前 IP:未同步
189898
勿吐槽……
找左飞吐去
引用
评论
加载评论中,请稍候...
200字以内,仅用于支线交流,主线讨论请采用回复功能。
折叠评论
phpskycn作者
14年11个月前 IP:未同步
190239
对着屏幕居然也可以……
引用
评论
加载评论中,请稍候...
200字以内,仅用于支线交流,主线讨论请采用回复功能。
折叠评论

想参与大家的讨论?现在就 登录 或者 注册

所属专业
上级专业
同级专业
phpskycn
专家 老干部 学者 机友 笔友
文章
402
回复
4591
学术分
8
2009/03/15注册,2个月3天前活动

CV

主体类型:个人
所属领域:无
认证方式:手机号
IP归属地:未同步
文件下载
加载中...
{{errorInfo}}
{{downloadWarning}}
你在 {{downloadTime}} 下载过当前文件。
文件名称:{{resource.defaultFile.name}}
下载次数:{{resource.hits}}
上传用户:{{uploader.username}}
所需积分:{{costScores}},{{holdScores}}下载当前附件免费{{description}}
积分不足,去充值
文件已丢失

当前账号的附件下载数量限制如下:
时段 个数
{{f.startingTime}}点 - {{f.endTime}}点 {{f.fileCount}}
视频暂不能访问,请登录试试
仅供内部学术交流或培训使用,请先保存到本地。本内容不代表科创观点,未经原作者同意,请勿转载。
音频暂不能访问,请登录试试
支持的图片格式:jpg, jpeg, png
插入公式
评论控制
加载中...
文号:{{pid}}
投诉或举报
加载中...
{{tip}}
请选择违规类型:
{{reason.type}}

空空如也

加载中...
详情
详情
推送到专栏从专栏移除
设为匿名取消匿名
查看作者
回复
只看作者
加入收藏取消收藏
收藏
取消收藏
折叠回复
置顶取消置顶
评学术分
鼓励
设为精选取消精选
管理提醒
编辑
通过审核
评论控制
退修或删除
历史版本
违规记录
投诉或举报
加入黑名单移除黑名单
查看IP
{{format('YYYY/MM/DD HH:mm:ss', toc)}}