=====================版权声明=======================
此代码来自电子工业出版社的《数字图象处理开发》一书所附光盘,
版权归原作者 左飞 万晋森 刘航 所有。
未经原作者允许,请勿用于商业用途,否则后果自负!
===================================================
*请使用Visual C++ 2005或以上版本,对BCB兼容性未测试
完整源代码下载:
第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"
200字以内,仅用于支线交流,主线讨论请采用回复功能。