OpenCV人脸识别代码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhanghm1995/article/details/84328096

本博客直接调用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

即可实现打开电脑摄像头进行人脸识别功能了。

猜你喜欢

转载自blog.csdn.net/zhanghm1995/article/details/84328096