Facemark.java 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import org.opencv.core.*;
  2. import org.opencv.face.*;
  3. import org.opencv.imgcodecs.*;
  4. import org.opencv.imgproc.*;
  5. import org.opencv.objdetect.*;
  6. import java.util.*;
  7. public class Facemark {
  8. static {
  9. System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  10. }
  11. public static void main(String[] args) {
  12. if (args.length < 3) {
  13. System.out.println("use: java Facemark [image file] [cascade file] [model file]");
  14. return;
  15. }
  16. // read the image
  17. Mat img = Imgcodecs.imread(args[0]);
  18. // setup face detection
  19. CascadeClassifier cascade = new CascadeClassifier(args[1]);
  20. MatOfRect faces = new MatOfRect();
  21. // detect faces
  22. cascade.detectMultiScale(img, faces);
  23. // setup landmarks detector
  24. Facemark fm = Face.createFacemarkKazemi();
  25. fm.loadModel(args[2]);
  26. // fit landmarks for each found face
  27. ArrayList<MatOfPoint2f> landmarks = new ArrayList<MatOfPoint2f>();
  28. fm.fit(img, faces, landmarks);
  29. // draw them
  30. for (int i=0; i<landmarks.size(); i++) {
  31. MatOfPoint2f lm = landmarks.get(i);
  32. for (int j=0; j<lm.rows(); j++) {
  33. double [] dp = lm.get(j,0);
  34. Point p = new Point(dp[0], dp[1]);
  35. Imgproc.circle(img,p,2,new Scalar(222),1);
  36. }
  37. }
  38. // save result
  39. Imgcodecs.imwrite("landmarks.jpg",img);
  40. }
  41. }