facialLandmarkDetection.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include <opencv2/opencv.hpp>
  2. #include <opencv2/face.hpp>
  3. #include "drawLandmarks.hpp"
  4. using namespace std;
  5. using namespace cv;
  6. using namespace cv::face;
  7. int main(int argc,char** argv)
  8. {
  9. // Load Face Detector
  10. CascadeClassifier faceDetector("haarcascade_frontalface_alt2.xml");
  11. // Create an instance of Facemark
  12. Ptr<Facemark> facemark = FacemarkLBF::create();
  13. // Load landmark detector
  14. facemark->loadModel("lbfmodel.yaml");
  15. // Set up webcam for video capture
  16. VideoCapture cam(0);
  17. // Variable to store a video frame and its grayscale
  18. Mat frame, gray;
  19. // Read a frame
  20. while(cam.read(frame))
  21. {
  22. // Find face
  23. vector<Rect> faces;
  24. // Convert frame to grayscale because
  25. // faceDetector requires grayscale image.
  26. cvtColor(frame, gray, COLOR_BGR2GRAY);
  27. // Detect faces
  28. faceDetector.detectMultiScale(gray, faces);
  29. // Variable for landmarks.
  30. // Landmarks for one face is a vector of points
  31. // There can be more than one face in the image. Hence, we
  32. // use a vector of vector of points.
  33. vector< vector<Point2f> > landmarks;
  34. // Run landmark detector
  35. bool success = facemark->fit(frame,faces,landmarks);
  36. if(success)
  37. {
  38. // If successful, render the landmarks on the face
  39. for(int i = 0; i < landmarks.size(); i++)
  40. {
  41. drawLandmarks(frame, landmarks[i]);
  42. }
  43. }
  44. // Display results
  45. imshow("Facial Landmark Detection", frame);
  46. // Exit loop if ESC is pressed
  47. if (waitKey(1) == 27) break;
  48. }
  49. return 0;
  50. }