1. 程式人生 > >OpenCV人臉識別程式碼

OpenCV人臉識別程式碼

本部落格直接呼叫OpenCV2.4.13附帶的訓練好的人臉檢測分類器,使用AdaBoost方法對電腦自帶攝像頭進行人臉識別。
face_detection.cpp:

#include <stdio.h>
#include <iostream>
#include <string>
//OpenCV
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"



using namespace std;
using namespace cv; std::string face_cascade_name = "haarcascade_frontalface_alt.xml"; CascadeClassifier face_cascade; string window_name = "Face detection"; //detect your face void DetectObject(cv::Mat& frame){ namedWindow(window_name,CV_WINDOW_NORMAL); std::vector<Rect> faces; Mat frame_gray;
cvtColor(frame, frame_gray, COLOR_BGR2GRAY); //equalizeHist(frame_gray, frame_gray);//直方圖均衡化 //-- 人臉檢測 face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30)); for (size_t i = 0; i < faces.size(); i++) { Point center(faces[i].x + faces[i].width / 2, faces[i]
.y + faces[i].height / 2); int radius = cvRound((faces[i].width + faces[i].height)*0.25); cv::circle(frame, center, radius, cv::Scalar(255, 0, 0),3);//draw circle //cv::rectangle(frame, faces[i], cv::Scalar(0, 255, 0), 4);//draw rectangle } //-- 顯示最終效果圖 imshow(window_name, frame); } int main( void ) { //-- 1. 載入級聯(cascades) if( !face_cascade.load( face_cascade_name ) ){ printf("no cascade file!!\n"); return -1; }; //-- 2. 讀取視訊 VideoCapture capture; Mat frame; cout<<"begin to open camera"<<endl; capture.open(1); //open the camera if( capture.isOpened() ) { cout<<"camera is opened!"<<endl; for(;;) { capture >> frame; //-- 3. 對當前幀使用分類器(Apply the classifier to the frame) if( !frame.empty() ) { DetectObject(frame); } else { printf("No captured frame!!"); break; } waitKey(50); } } else { cout<<"Opps,Cannot open the camera!!"<<endl; } return 0; }

同目錄下建立CMakeLists.txt檔案:

cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
project(face_detection)
if(NOT CMAKE_BUILD_TYPE)
  set(POSSIBLE_BUILD_TYPES "Debug Release RelWithDebInfo MinSizeRel")
  set(CMAKE_BUILD_TYPE "Release" CACHE STRING
      "Choose the type of build, options are: ${POSSIBLE_BUILD_TYPES}." FORCE)
endif(NOT CMAKE_BUILD_TYPE)
message(STATUS "CMAKE_BUILD_TYPE: " ${CMAKE_BUILD_TYPE})

#find package
find_package(OpenCV 2.4.13 REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})

add_executable(face_detection face_detection.cpp)
target_link_libraries(face_detection ${OpenCV_LIBS})

Ubuntu下在該檔案根目錄下開啟終端,執行:

mkdir build
cd build
cmake ..
make -j6

會生成一個可執行檔案face_detection
將OpenCV自帶的haarcascade_frontalface_alt.xml檔案拷貝至build目錄下,執行:

./face_detection

即可實現開啟電腦攝像頭進行人臉識別功能了。