face_detection_opencv_haar.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include "opencv2/objdetect.hpp"
  2. #include "opencv2/videoio.hpp"
  3. #include "opencv2/highgui.hpp"
  4. #include "opencv2/imgproc.hpp"
  5. #include <iostream>
  6. #include <stdio.h>
  7. using namespace std;
  8. using namespace cv;
  9. /** Global variables */
  10. String faceCascadePath;
  11. CascadeClassifier faceCascade;
  12. void detectFaceOpenCVHaar(CascadeClassifier faceCascade, Mat &frameOpenCVHaar, int inHeight=300, int inWidth=0)
  13. {
  14. int frameHeight = frameOpenCVHaar.rows;
  15. int frameWidth = frameOpenCVHaar.cols;
  16. if (!inWidth)
  17. inWidth = (int)((frameWidth / (float)frameHeight) * inHeight);
  18. float scaleHeight = frameHeight / (float)inHeight;
  19. float scaleWidth = frameWidth / (float)inWidth;
  20. Mat frameOpenCVHaarSmall, frameGray;
  21. resize(frameOpenCVHaar, frameOpenCVHaarSmall, Size(inWidth, inHeight));
  22. cvtColor(frameOpenCVHaarSmall, frameGray, COLOR_BGR2GRAY);
  23. std::vector<Rect> faces;
  24. faceCascade.detectMultiScale(frameGray, faces);
  25. for ( size_t i = 0; i < faces.size(); i++ )
  26. {
  27. int x1 = (int)(faces[i].x * scaleWidth);
  28. int y1 = (int)(faces[i].y * scaleHeight);
  29. int x2 = (int)((faces[i].x + faces[i].width) * scaleWidth);
  30. int y2 = (int)((faces[i].y + faces[i].height) * scaleHeight);
  31. rectangle(frameOpenCVHaar, Point(x1, y1), Point(x2, y2), Scalar(0,255,0), (int)(frameHeight/150.0), 4);
  32. }
  33. }
  34. int main( int argc, const char** argv )
  35. {
  36. faceCascadePath = "models/haarcascade_frontalface_default.xml";
  37. if(!faceCascade.load(faceCascadePath))
  38. {
  39. printf("--(!)Error loading face cascade\n");
  40. return -1;
  41. }
  42. VideoCapture source;
  43. if (argc == 1)
  44. source.open(0, CAP_V4L);
  45. else
  46. source.open(argv[1]); Mat frame;
  47. double tt_opencvHaar = 0;
  48. double fpsOpencvHaar = 0;
  49. while (true)
  50. {
  51. source >> frame;
  52. if (frame.empty())
  53. break;
  54. double t = cv::getTickCount();
  55. detectFaceOpenCVHaar(faceCascade, frame);
  56. tt_opencvHaar = ((double)cv::getTickCount() - t)/cv::getTickFrequency();
  57. fpsOpencvHaar = 1/tt_opencvHaar;
  58. putText(frame, format("OpenCV HAAR ; FPS = %.2f",fpsOpencvHaar), Point(10, 50), FONT_HERSHEY_SIMPLEX, 1.3, Scalar(0, 0, 255), 4);
  59. imshow("OpenCV - HAAR Face Detection", frame);
  60. int k = waitKey(5);
  61. if(k == 27)
  62. {
  63. destroyAllWindows();
  64. break;
  65. }
  66. }
  67. }