天天看點

Dlib提取人臉特征點

轉自https://blog.csdn.net/zmdsjtu/article/details/53454071?ticket=ST-3153-47Plcph2ez6yRnbTZqXP-passport.csdn.net

主要在官網給的Demo基礎之上用Opencv把特征點描繪出來了。

很早之前寫過一篇配置Dlib環境的部落格,現在來稍微梳理下提取特征點的使用方法。

上一篇配置環境部落格位址:http://blog.csdn.net/zmdsjtu/article/details/52422847

慣例先放效果圖吧:

Dlib提取人臉特征點

動圖如下:

Dlib提取人臉特征點

接着就是簡單粗暴的代碼:

  1. //@[email protected]
  2. //2016-12-4
  3. //http://blog.csdn.net/zmdsjtu/article/details/53454071
  4. #include <dlib/opencv.h>
  5. #include <opencv2/opencv.hpp>
  6. #include <dlib/image_processing/frontal_face_detector.h>
  7. #include <dlib/image_processing/render_face_detections.h>
  8. #include <dlib/image_processing.h>
  9. #include <dlib/gui_widgets.h>
  10. using namespace dlib;
  11. using namespace std;
  12. int main()
  13. {
  14. try
  15. {
  16. cv:: VideoCapture cap();
  17. if (!cap.isOpened())
  18. {
  19. cerr << "Unable to connect to camera" << endl;
  20. return ;
  21. }
  22. //image_window win;
  23. // Load face detection and pose estimation models.
  24. frontal_face_detector detector = get_frontal_face_detector();
  25. shape_predictor pose_model;
  26. deserialize( "shape_predictor_68_face_landmarks.dat") >> pose_model;
  27. // Grab and process frames until the main window is closed by the user.
  28. while (cv::waitKey( ) != )
  29. {
  30. // Grab a frame
  31. cv::Mat temp;
  32. cap >> temp;
  33. cv_image<bgr_pixel> cimg(temp);
  34. // Detect faces
  35. std:: vector<rectangle> faces = detector(cimg);
  36. // Find the pose of each face.
  37. std:: vector<full_object_detection> shapes;
  38. for ( unsigned long i = ; i < faces.size(); ++i)
  39. shapes.push_back(pose_model(cimg, faces[i]));
  40. if (!shapes.empty()) {
  41. for ( int i = ; i < ; i++) {
  42. circle(temp, cvPoint(shapes[ ].part(i).x(), shapes[ ].part(i).y()), , cv::Scalar( , , ), );
  43. // shapes[0].part(i).x();//68個
  44. }
  45. }
  46. //Display it all on the screen
  47. imshow( "Dlib特征點", temp);
  48. }
  49. }
  50. catch (serialization_error& e)
  51. {
  52. cout << "You need dlib's default face landmarking model file to run this example." << endl;
  53. cout << "You can get it from the following URL: " << endl;
  54. cout << " http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2" << endl;
  55. cout << endl << e.what() << endl;
  56. }
  57. catch (exception& e)
  58. {
  59. cout << e.what() << endl;
  60. }
  61. }

來看下上面那段代碼,所有的需要的特征點都存儲在Shapes裡。仔細看看下面這行代碼:

circle(temp, cvPoint(shapes[].part(i).x(), shapes[].part(i).y()), , cv::Scalar(, , ), );
           

可以看到shpes[0]代表的是第一個人(可以同時檢測到很多個人),part(i)代表的是第i個特征點,x()和y()是通路特征點坐标的途徑。

每個特征點的編号如下:

在上述畫圖的基礎上加了如下一行代碼:

putText(temp, to_string(i), cvPoint(shapes[].part(i).x(), shapes[].part(i).y()), CV_FONT_HERSHEY_PLAIN, , cv::Scalar(, , ),,);
           

效果圖:

Dlib提取人臉特征點

對照着上圖,比如說想擷取鼻尖的坐标,那麼橫坐标就是shapes[0].part[30].x(),其餘的類似。

在這個的基礎上就可以做很多有意思的事情啦,2333

最後祝大家開發愉快:)

繼續閱讀