Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.user.testjavacv;
- import android.content.Context;
- import android.util.Log;
- import android.widget.Toast;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.FilenameFilter;
- import java.io.IOException;
- import java.io.InputStream;
- import java.nio.IntBuffer;
- import java.util.ArrayList;
- import java.util.List;
- import static org.bytedeco.javacpp.opencv_core.CV_32SC1;
- import org.bytedeco.javacpp.opencv_core;
- import org.bytedeco.javacpp.opencv_core.Mat;
- import org.bytedeco.javacpp.opencv_core.MatVector;
- import org.bytedeco.javacpp.opencv_core.Size;
- import org.bytedeco.javacpp.opencv_face.FaceRecognizer;
- import org.bytedeco.javacpp.opencv_objdetect;
- import static org.bytedeco.javacpp.opencv_imgcodecs.imwrite;
- import static org.bytedeco.javacpp.opencv_imgproc.rectangle;
- import static org.bytedeco.javacpp.opencv_face.EigenFaceRecognizer;
- import static org.bytedeco.javacpp.opencv_face.FisherFaceRecognizer;
- import static org.bytedeco.javacpp.opencv_face.LBPHFaceRecognizer;
- import static org.bytedeco.javacpp.opencv_imgcodecs.CV_LOAD_IMAGE_GRAYSCALE;
- import static org.bytedeco.javacpp.opencv_imgcodecs.imread;
- import static org.bytedeco.javacpp.opencv_imgproc.CV_BGR2GRAY;
- import static org.bytedeco.javacpp.opencv_imgproc.cvtColor;
- import static org.bytedeco.javacpp.opencv_imgproc.resize;
- public class TrainHelper {
- public static final String TAG = "TrainHelper";
- public static final String TRAIN_FOLDER = "train_folder";
- public static final String UPLOAD_FOLDER = "upload_folder";
- public static final int IMG_SIZE = 128;
- public static final String EIGEN_FACES_CLASSIFIER = "eigenFacesClassifier.yml";
- public static final String FISHER_FACES_CLASSIFIER = "fisherFacesClassifier.yml";
- public static final String LBPH_CLASSIFIER = "lbphClassifier.yml";
- public static final String FILE_NAME_PATTERN = "person.%d.%d.jpg";
- public static final int PHOTOS_TRAIN_QTY = 25;
- public static final double LBPH_ACCEPT_LEVEL = 75.0D;
- public static final double ACCEPT_LEVEL = 3000.0D;
- public static void reset(Context context) throws Exception {
- File photosFolder = new File(context.getFilesDir(), TRAIN_FOLDER);
- if(photosFolder.exists()) {
- FilenameFilter imageFilter = new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- return name.endsWith(".jpg") || name.endsWith(".gif") || name.endsWith(".png") ||name.endsWith(".yml");
- }
- };
- File[] files = photosFolder.listFiles(imageFilter);
- for(File file : files) {
- file.delete();
- }
- }
- }
- public static boolean isTrained(Context context) {
- try {
- File photosFolder = new File(context.getFilesDir(), TRAIN_FOLDER);
- if(photosFolder.exists()) {
- FilenameFilter imageFilter = new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- return name.endsWith(".jpg") || name.endsWith(".gif") || name.endsWith(".png");
- }
- };
- FilenameFilter trainFilter = new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- return name.endsWith(".yml");
- }
- };
- File[] photos = photosFolder.listFiles(imageFilter);
- File[] train = photosFolder.listFiles(trainFilter);
- return (photos != null && train != null && photos.length > 0 && train.length > 0);
- } else {
- return false;
- }
- }catch (Exception e) {
- Log.d(TAG, e.getLocalizedMessage(), e);
- }
- return false;
- }
- public static int qtdPhotos(Context context) {
- File photosFolder = new File(context.getFilesDir(), TRAIN_FOLDER);
- if(photosFolder.exists()) {
- FilenameFilter imageFilter = new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- return name.endsWith(".jpg") || name.endsWith(".gif") || name.endsWith(".png");
- }
- };
- File[] files = photosFolder.listFiles(imageFilter);
- return files != null ? files.length : 0;
- }
- return 0;
- }
- public static boolean train(Context context, FaceRecognizer faceRecognizer, String type, List<String> nameList) throws Exception {
- if (type == null) type = "Eigenfaces";
- File photosFolder = new File(context.getFilesDir(), TRAIN_FOLDER);
- if(!photosFolder.exists()) return false;
- FilenameFilter imageFilter = new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- return name.endsWith(".jpg") || name.endsWith(".gif") || name.endsWith(".png");
- }
- };
- nameList = new ArrayList<String>();
- List<Integer> namesIntList = new ArrayList<>();
- File[] files = photosFolder.listFiles(imageFilter);
- MatVector photos = new MatVector(files.length);
- Mat labels = new Mat(files.length, 1, CV_32SC1);
- IntBuffer rotulosBuffer = labels.createBuffer();
- int counter = 0;
- for (File image: files) {
- Mat photo = imread(image.getAbsolutePath(), CV_LOAD_IMAGE_GRAYSCALE);
- resize(photo, photo, new Size(IMG_SIZE, IMG_SIZE));
- photos.put(counter, photo);
- String name = image.getName().split("\\.")[0];
- if (!nameList.contains(name)){
- nameList.add(name);
- }
- namesIntList.add(nameList.indexOf(name));
- rotulosBuffer.put(counter, nameList.indexOf(name));
- counter++;
- }
- if (type.equals("LBPH")) {
- // faceRecognizer = createLBPHFaceRecognizer(2,9,9,9,1);
- faceRecognizer = LBPHFaceRecognizer.create(1, 8, 8, 8, 300);
- faceRecognizer.train(photos, labels);
- File f = new File(photosFolder, LBPH_CLASSIFIER);
- f.createNewFile();
- faceRecognizer.save(f.getAbsolutePath());
- } else if (type.equals("Fisherfaces")) {
- faceRecognizer = FisherFaceRecognizer.create();
- faceRecognizer.train(photos, labels);
- File f = new File(photosFolder, FISHER_FACES_CLASSIFIER);
- f.createNewFile();
- faceRecognizer.save(f.getAbsolutePath());
- } else if (type.equals("Eigenfaces")) {
- faceRecognizer = EigenFaceRecognizer.create();
- faceRecognizer.train(photos, labels);
- File f = new File(photosFolder, EIGEN_FACES_CLASSIFIER);
- f.createNewFile();
- faceRecognizer.save(f.getAbsolutePath());
- } else {
- faceRecognizer = EigenFaceRecognizer.create();
- faceRecognizer.train(photos, labels);
- File f = new File(photosFolder, EIGEN_FACES_CLASSIFIER);
- f.createNewFile();
- faceRecognizer.save(f.getAbsolutePath());
- }
- Toast.makeText(context, "Upload Completed!", Toast.LENGTH_SHORT).show();
- return true;
- }
- public static void takeFacePhoto(Context context, int personId, int photoNumber, Mat rgbaMat, opencv_objdetect.CascadeClassifier faceDetector, String personName) throws Exception{
- if (personName == null) {
- personName = FILE_NAME_PATTERN;
- } else {
- personName = personName + ".%d.%d.jpg";
- }
- File folder = new File(context.getFilesDir(), TRAIN_FOLDER);
- if (folder.exists() && !folder.isDirectory())
- folder.delete();
- if (!folder.exists())
- folder.mkdirs();
- int qtyPhotos = PHOTOS_TRAIN_QTY;
- Mat greyMat = new Mat(rgbaMat.rows(), rgbaMat.cols());
- cvtColor(rgbaMat, greyMat, CV_BGR2GRAY);
- opencv_core.RectVector detectedFaces = new opencv_core.RectVector();
- faceDetector.detectMultiScale(greyMat, detectedFaces, 1.1, 1, 0, new Size(150,150), new Size(500,500));
- for (int i = 0; i < detectedFaces.size(); i++) {
- opencv_core.Rect rectFace = detectedFaces.get(0);
- rectangle(rgbaMat, rectFace, new opencv_core.Scalar(0,0,255, 0));
- Mat capturedFace = new Mat(greyMat, rectFace);
- resize(capturedFace, capturedFace, new Size(IMG_SIZE,IMG_SIZE));
- if (photoNumber <= qtyPhotos) {
- File f = new File(folder, String.format(personName, personId, photoNumber));
- f.createNewFile();
- imwrite(f.getAbsolutePath(), capturedFace);
- }
- }
- }
- public static opencv_objdetect.CascadeClassifier loadClassifierCascade(Context context, int resId) {
- FileOutputStream fos = null;
- InputStream inputStream;
- inputStream = context.getResources().openRawResource(resId);
- File xmlDir = context.getDir("xml", Context.MODE_PRIVATE);
- File cascadeFile = new File(xmlDir, "temp.xml");
- try {
- fos = new FileOutputStream(cascadeFile);
- byte[] buffer = new byte[4096];
- int bytesRead;
- while ((bytesRead = inputStream.read(buffer)) != -1) {
- fos.write(buffer, 0, bytesRead);
- }
- } catch (IOException e) {
- Log.d(TAG, "Can\'t load the cascade file");
- e.printStackTrace();
- } finally {
- if (inputStream != null) {
- try {
- inputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (fos != null) {
- try {
- fos.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- opencv_objdetect.CascadeClassifier detector = new opencv_objdetect.CascadeClassifier(cascadeFile.getAbsolutePath());
- if (detector.isNull()) {
- Log.e(TAG, "Failed to load cascade classifier");
- detector = null;
- } else {
- Log.i(TAG, "Loaded cascade classifier from " + cascadeFile.getAbsolutePath());
- }
- // delete the temporary directory
- cascadeFile.delete();
- return detector;
- }
- public static int getPersonId(Context context) {
- // Get last count
- File photosFolder = new File(context.getFilesDir(), TrainHelper.TRAIN_FOLDER);
- FilenameFilter imageFilter = new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- return name.endsWith(".jpg") || name.endsWith(".gif") || name.endsWith(".png");
- }
- };
- File[] files = photosFolder.listFiles(imageFilter);
- int personId = 1;
- String tempName = "";
- if (files != null) {
- for (File image : files) {
- String name = image.getName().split("\\.")[0];
- Log.i(TAG, "name : " + name);
- if (tempName.equals("")) {
- tempName = name;
- personId++;
- } else {
- if (!tempName.equals(name)) {
- tempName = name;
- personId++;
- }
- }
- Log.i(TAG, "personId : " + personId);
- }
- }
- return personId;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment