ronaldkwandy

TrainHelper

May 11th, 2018
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.70 KB | None | 0 0
  1. package com.example.user.testjavacv;
  2.  
  3. import android.content.Context;
  4. import android.util.Log;
  5. import android.widget.Toast;
  6.  
  7. import java.io.File;
  8. import java.io.FileOutputStream;
  9. import java.io.FilenameFilter;
  10. import java.io.IOException;
  11. import java.io.InputStream;
  12. import java.nio.IntBuffer;
  13. import java.util.ArrayList;
  14. import java.util.List;
  15.  
  16. import static org.bytedeco.javacpp.opencv_core.CV_32SC1;
  17.  
  18. import org.bytedeco.javacpp.opencv_core;
  19. import org.bytedeco.javacpp.opencv_core.Mat;
  20. import org.bytedeco.javacpp.opencv_core.MatVector;
  21. import org.bytedeco.javacpp.opencv_core.Size;
  22. import org.bytedeco.javacpp.opencv_face.FaceRecognizer;
  23. import org.bytedeco.javacpp.opencv_objdetect;
  24.  
  25. import static org.bytedeco.javacpp.opencv_imgcodecs.imwrite;
  26. import static org.bytedeco.javacpp.opencv_imgproc.rectangle;
  27.  
  28. import static org.bytedeco.javacpp.opencv_face.EigenFaceRecognizer;
  29. import static org.bytedeco.javacpp.opencv_face.FisherFaceRecognizer;
  30. import static org.bytedeco.javacpp.opencv_face.LBPHFaceRecognizer;
  31. import static org.bytedeco.javacpp.opencv_imgcodecs.CV_LOAD_IMAGE_GRAYSCALE;
  32. import static org.bytedeco.javacpp.opencv_imgcodecs.imread;
  33. import static org.bytedeco.javacpp.opencv_imgproc.CV_BGR2GRAY;
  34. import static org.bytedeco.javacpp.opencv_imgproc.cvtColor;
  35. import static org.bytedeco.javacpp.opencv_imgproc.resize;
  36.  
  37. public class TrainHelper {
  38.  
  39.     public static final String TAG = "TrainHelper";
  40.     public static final String TRAIN_FOLDER = "train_folder";
  41.     public static final String UPLOAD_FOLDER = "upload_folder";
  42.     public static final int IMG_SIZE = 128;
  43.  
  44.     public static final String EIGEN_FACES_CLASSIFIER = "eigenFacesClassifier.yml";
  45.     public static final String FISHER_FACES_CLASSIFIER = "fisherFacesClassifier.yml";
  46.     public static final String LBPH_CLASSIFIER = "lbphClassifier.yml";
  47.     public static final String FILE_NAME_PATTERN = "person.%d.%d.jpg";
  48.     public static final int PHOTOS_TRAIN_QTY = 25;
  49.     public static final double LBPH_ACCEPT_LEVEL = 75.0D;
  50.     public static final double ACCEPT_LEVEL = 3000.0D;
  51.  
  52.  
  53.     public static void reset(Context context) throws Exception {
  54.         File photosFolder = new File(context.getFilesDir(), TRAIN_FOLDER);
  55.         if(photosFolder.exists()) {
  56.  
  57.             FilenameFilter imageFilter = new FilenameFilter() {
  58.                 @Override
  59.                 public boolean accept(File dir, String name) {
  60.                     return  name.endsWith(".jpg") || name.endsWith(".gif") || name.endsWith(".png")  ||name.endsWith(".yml");
  61.                 }
  62.             };
  63.  
  64.             File[] files = photosFolder.listFiles(imageFilter);
  65.             for(File file : files) {
  66.                 file.delete();
  67.             }
  68.         }
  69.     }
  70.  
  71.  
  72.     public static boolean isTrained(Context context) {
  73.         try {
  74.             File photosFolder = new File(context.getFilesDir(), TRAIN_FOLDER);
  75.             if(photosFolder.exists()) {
  76.  
  77.                 FilenameFilter imageFilter = new FilenameFilter() {
  78.                     @Override
  79.                     public boolean accept(File dir, String name) {
  80.                         return  name.endsWith(".jpg") || name.endsWith(".gif") || name.endsWith(".png");
  81.                     }
  82.                 };
  83.  
  84.                 FilenameFilter trainFilter = new FilenameFilter() {
  85.                     @Override
  86.                     public boolean accept(File dir, String name) {
  87.                         return  name.endsWith(".yml");
  88.                     }
  89.                 };
  90.  
  91.                 File[] photos = photosFolder.listFiles(imageFilter);
  92.                 File[] train = photosFolder.listFiles(trainFilter);
  93.  
  94.                 return (photos != null && train != null && photos.length > 0 && train.length > 0);
  95.             } else {
  96.                 return false;
  97.             }
  98.  
  99.         }catch (Exception e) {
  100.             Log.d(TAG, e.getLocalizedMessage(), e);
  101.         }
  102.         return false;
  103.     }
  104.  
  105.     public static int qtdPhotos(Context context) {
  106.         File photosFolder = new File(context.getFilesDir(), TRAIN_FOLDER);
  107.         if(photosFolder.exists()) {
  108.             FilenameFilter imageFilter = new FilenameFilter() {
  109.                 @Override
  110.                 public boolean accept(File dir, String name) {
  111.                     return  name.endsWith(".jpg") || name.endsWith(".gif") || name.endsWith(".png");
  112.                 }
  113.             };
  114.  
  115.             File[] files = photosFolder.listFiles(imageFilter);
  116.             return files != null ? files.length : 0;
  117.         }
  118.         return 0;
  119.     }
  120.  
  121.     public static boolean train(Context context, FaceRecognizer faceRecognizer, String type, List<String> nameList) throws Exception {
  122.         if (type == null) type = "Eigenfaces";
  123.  
  124.         File photosFolder = new File(context.getFilesDir(), TRAIN_FOLDER);
  125.         if(!photosFolder.exists()) return false;
  126.  
  127.         FilenameFilter imageFilter = new FilenameFilter() {
  128.             @Override
  129.             public boolean accept(File dir, String name) {
  130.                 return  name.endsWith(".jpg") || name.endsWith(".gif") || name.endsWith(".png");
  131.             }
  132.         };
  133.  
  134.         nameList = new ArrayList<String>();
  135.         List<Integer> namesIntList = new ArrayList<>();
  136.  
  137.         File[] files = photosFolder.listFiles(imageFilter);
  138.         MatVector photos = new MatVector(files.length);
  139.         Mat labels = new Mat(files.length, 1, CV_32SC1);
  140.         IntBuffer rotulosBuffer = labels.createBuffer();
  141.         int counter = 0;
  142.         for (File image: files) {
  143.             Mat photo = imread(image.getAbsolutePath(), CV_LOAD_IMAGE_GRAYSCALE);
  144.             resize(photo, photo, new Size(IMG_SIZE, IMG_SIZE));
  145.             photos.put(counter, photo);
  146.  
  147.             String name = image.getName().split("\\.")[0];
  148.             if (!nameList.contains(name)){
  149.                 nameList.add(name);
  150.             }
  151.             namesIntList.add(nameList.indexOf(name));
  152.  
  153.             rotulosBuffer.put(counter, nameList.indexOf(name));
  154.             counter++;
  155.         }
  156.  
  157.         if (type.equals("LBPH")) {
  158. //            faceRecognizer = createLBPHFaceRecognizer(2,9,9,9,1);
  159.             faceRecognizer = LBPHFaceRecognizer.create(1, 8, 8, 8, 300);
  160.  
  161.             faceRecognizer.train(photos, labels);
  162.             File f = new File(photosFolder, LBPH_CLASSIFIER);
  163.             f.createNewFile();
  164.             faceRecognizer.save(f.getAbsolutePath());
  165.         } else if (type.equals("Fisherfaces")) {
  166.             faceRecognizer = FisherFaceRecognizer.create();
  167.  
  168.             faceRecognizer.train(photos, labels);
  169.             File f = new File(photosFolder, FISHER_FACES_CLASSIFIER);
  170.             f.createNewFile();
  171.             faceRecognizer.save(f.getAbsolutePath());
  172.         } else if (type.equals("Eigenfaces")) {
  173.             faceRecognizer = EigenFaceRecognizer.create();
  174.  
  175.             faceRecognizer.train(photos, labels);
  176.             File f = new File(photosFolder, EIGEN_FACES_CLASSIFIER);
  177.             f.createNewFile();
  178.             faceRecognizer.save(f.getAbsolutePath());
  179.         } else {
  180.             faceRecognizer = EigenFaceRecognizer.create();
  181.  
  182.             faceRecognizer.train(photos, labels);
  183.             File f = new File(photosFolder, EIGEN_FACES_CLASSIFIER);
  184.             f.createNewFile();
  185.             faceRecognizer.save(f.getAbsolutePath());
  186.         }
  187.  
  188.         Toast.makeText(context, "Upload Completed!", Toast.LENGTH_SHORT).show();
  189.         return true;
  190.     }
  191.  
  192.     public static void takeFacePhoto(Context context, int personId, int photoNumber, Mat rgbaMat, opencv_objdetect.CascadeClassifier faceDetector, String personName) throws Exception{
  193.         if (personName == null) {
  194.             personName = FILE_NAME_PATTERN;
  195.         } else {
  196.             personName = personName + ".%d.%d.jpg";
  197.         }
  198.  
  199.         File folder = new File(context.getFilesDir(), TRAIN_FOLDER);
  200.         if (folder.exists() && !folder.isDirectory())
  201.             folder.delete();
  202.         if (!folder.exists())
  203.             folder.mkdirs();
  204.  
  205.         int qtyPhotos = PHOTOS_TRAIN_QTY;
  206.         Mat greyMat = new Mat(rgbaMat.rows(), rgbaMat.cols());
  207.  
  208.         cvtColor(rgbaMat, greyMat, CV_BGR2GRAY);
  209.         opencv_core.RectVector detectedFaces = new opencv_core.RectVector();
  210.         faceDetector.detectMultiScale(greyMat, detectedFaces, 1.1, 1, 0, new Size(150,150), new Size(500,500));
  211.         for (int i = 0; i < detectedFaces.size(); i++) {
  212.  
  213.             opencv_core.Rect rectFace = detectedFaces.get(0);
  214.             rectangle(rgbaMat, rectFace, new opencv_core.Scalar(0,0,255, 0));
  215.             Mat capturedFace = new Mat(greyMat, rectFace);
  216.             resize(capturedFace, capturedFace, new Size(IMG_SIZE,IMG_SIZE));
  217.  
  218.             if (photoNumber <= qtyPhotos) {
  219.                 File f = new File(folder, String.format(personName, personId, photoNumber));
  220.                 f.createNewFile();
  221.                 imwrite(f.getAbsolutePath(), capturedFace);
  222.             }
  223.         }
  224.     }
  225.  
  226.  
  227.     public static opencv_objdetect.CascadeClassifier loadClassifierCascade(Context context, int resId) {
  228.         FileOutputStream fos = null;
  229.         InputStream inputStream;
  230.  
  231.         inputStream = context.getResources().openRawResource(resId);
  232.         File xmlDir = context.getDir("xml", Context.MODE_PRIVATE);
  233.         File cascadeFile = new File(xmlDir, "temp.xml");
  234.         try {
  235.             fos = new FileOutputStream(cascadeFile);
  236.             byte[] buffer = new byte[4096];
  237.             int bytesRead;
  238.             while ((bytesRead = inputStream.read(buffer)) != -1) {
  239.                 fos.write(buffer, 0, bytesRead);
  240.             }
  241.         } catch (IOException e) {
  242.             Log.d(TAG, "Can\'t load the cascade file");
  243.             e.printStackTrace();
  244.         } finally {
  245.             if (inputStream != null) {
  246.                 try {
  247.                     inputStream.close();
  248.                 } catch (IOException e) {
  249.                     e.printStackTrace();
  250.                 }
  251.             }
  252.             if (fos != null) {
  253.                 try {
  254.                     fos.close();
  255.                 } catch (IOException e) {
  256.                     e.printStackTrace();
  257.                 }
  258.             }
  259.         }
  260.  
  261.         opencv_objdetect.CascadeClassifier detector = new opencv_objdetect.CascadeClassifier(cascadeFile.getAbsolutePath());
  262.         if (detector.isNull()) {
  263.             Log.e(TAG, "Failed to load cascade classifier");
  264.             detector = null;
  265.         } else {
  266.             Log.i(TAG, "Loaded cascade classifier from " + cascadeFile.getAbsolutePath());
  267.         }
  268.         // delete the temporary directory
  269.         cascadeFile.delete();
  270.  
  271.         return detector;
  272.     }
  273.  
  274.     public static int getPersonId(Context context) {
  275.         // Get last count
  276.         File photosFolder = new File(context.getFilesDir(), TrainHelper.TRAIN_FOLDER);
  277.         FilenameFilter imageFilter = new FilenameFilter() {
  278.             @Override
  279.             public boolean accept(File dir, String name) {
  280.                 return  name.endsWith(".jpg") || name.endsWith(".gif") || name.endsWith(".png");
  281.             }
  282.         };
  283.         File[] files = photosFolder.listFiles(imageFilter);
  284.         int personId = 1;
  285.         String tempName = "";
  286.         if (files != null) {
  287.             for (File image : files) {
  288.                 String name = image.getName().split("\\.")[0];
  289.                 Log.i(TAG, "name : " + name);
  290.                 if (tempName.equals("")) {
  291.                     tempName = name;
  292.                     personId++;
  293.                 }  else {
  294.                     if (!tempName.equals(name)) {
  295.                         tempName = name;
  296.                         personId++;
  297.                     }
  298.                 }
  299.                 Log.i(TAG, "personId : " + personId);
  300.             }
  301.         }
  302.         return personId;
  303.     }
  304. }
Advertisement
Add Comment
Please, Sign In to add comment