OpenCV例子四:摄像头实时人脸检测

以你之姓@ 2022-08-07 08:45 295阅读 0赞
  1. #include "stdafx.h"
  2. #include <iostream>
  3. #include <opencv2/imgproc/imgproc.hpp> // Gaussian Blur
  4. #include <opencv2/core/core.hpp> // Basic OpenCV structures (cv::Mat, Scalar)
  5. #include <opencv2/highgui/highgui.hpp> // OpenCV window I/O
  6. #include "opencv2/objdetect/objdetect.hpp"//人脸识别的接口
  7. using namespace cv;//必须加入,否则无法检找到OPENCV的各个函数
  8. using namespace std;
  9. string face_cascade_name = "haarcascade_frontalface_alt2.xml";
  10. CascadeClassifier face_cascade;
  11. string window_name = "人脸识别";
  12. void detectAndDisplay(Mat frame){
  13. std::vector<Rect> faces;
  14. Mat frame_gray;
  15. cvtColor( frame, frame_gray, CV_BGR2GRAY );
  16. equalizeHist( frame_gray, frame_gray );
  17. face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) );
  18. for( int i = 0; i < faces.size(); i++ ){
  19. Point center( faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5 );
  20. ellipse( frame, center, Size( faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 );
  21. }
  22. imshow(window_name, frame);
  23. }
  24. int _tmain(int argc, _TCHAR* argv[])
  25. {
  26. VideoCapture cap(0); // open the default camera
  27. if (!cap.isOpened()) // check if we succeeded
  28. return -1;
  29. Mat edges;
  30. //namedWindow("edges", 1);
  31. if (!face_cascade.load(face_cascade_name)){
  32. printf("[error] 无法加载级联分类器文件!\n");
  33. return -1;
  34. }
  35. int nTick = 0;
  36. for (;;)
  37. {
  38. if (!cap.isOpened())
  39. {//等等摄像头打开
  40. continue;
  41. }
  42. Mat frame;
  43. nTick = getTickCount();
  44. cap >> frame; // get a new frame from camera
  45. if (frame.data == NULL)
  46. {//等到捕获到数据
  47. continue;
  48. }
  49. cvtColor(frame, edges, CV_BGR2BGRA);
  50. detectAndDisplay(edges);
  51. if (waitKey(30) >= 0) break;
  52. }
  53. return 0;
  54. }

其中XML文件在data\haarcascades目录下。该目录下有很多脚本可以使用。比如眼睛检测、身体检测等等。

注意,将该文件拷贝到程序运行目录下。另外该程序没有进行优化,会暂用很高的CPU。使用前请注意。

  1. 来自:http://blog.csdn.net/lan120576664

发表评论

表情:
评论列表 (有 0 条评论,295人围观)

还没有评论,来说两句吧...

相关阅读