OpenCV人脸识别代码

导读:本篇文章讲解 OpenCV人脸识别代码,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/121286.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!