Domain.ImgProcess.java Source code

Java tutorial

Introduction

Here is the source code for Domain.ImgProcess.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Domain;

import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.IntBuffer;

import javax.imageio.ImageIO;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.highgui.Highgui;
import org.opencv.highgui.VideoCapture;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import static org.bytedeco.javacpp.opencv_contrib.*;
import static org.bytedeco.javacpp.opencv_core.*;
import static org.bytedeco.javacpp.opencv_highgui.*;

import DataAcces.SettingsDAO;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Gertrude
 */
public class ImgProcess {

    public Mat retornaFrame() {
        System.loadLibrary("opencv_java2410");
        /*opencv_java2410*/
        VideoCapture camera = new VideoCapture(0);//inicializa com o dispositivo de video #0

        camera.open(0);
        try {
            Thread.sleep(100);//necessario para a cmera poder ser inicializada
        } catch (InterruptedException ex) {
            System.out.printf(ex.getMessage());
        }

        if (camera.isOpened()) {

            System.out.println("Ta aberto");
        }

        Mat frame = new Mat();

        camera.read(frame);//captura o frame atual da cmera
        System.out.println("Frame adquirido.");
        camera.release();
        return frame;

    }

    public Mat DetectarFace(Canvas c, Mat image) throws IOException {
        System.out.println("Rodando DetectFace");

        CascadeClassifier faceDetector = new CascadeClassifier(
                "C:\\Users\\Gertrude\\Documents\\NetBeansProjects\\OWL_Sight\\src\\Resources\\lbpcascade_frontalface.xml"); // seleciona o classificador para identificao da face

        MatOfRect faceDetections = new MatOfRect(); //matriz de rectangulos representando os rosto encontrados
        faceDetector.detectMultiScale(image, faceDetections);//detecta multiplas faces na imagem fornecida

        System.out.printf("Detected %s faces", faceDetections.toArray().length);

        Mat corte = null;

        for (Rect rect : faceDetections.toArray()) {
            Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height),
                    new Scalar(0, 0, 0));// desenha os rectangulos

            // Highgui.imwrite("C:/TCC-FacialRecognize/src/resources/TESTECORTE.jpg", utl.corte(image, rect));
            corte = new Mat(image, rect);
        }

        Size sz = new Size(120, 120);

        MatOfByte bytemat = new MatOfByte(); //transformando a matriz image em uma matriz de bytes para carga no canvas do form principal
        Highgui.imencode(".jpg", corte, bytemat);
        byte[] bytes = bytemat.toArray();
        InputStream in = new ByteArrayInputStream(bytes);

        BufferedImage render = ImageIO.read(in);
        Graphics g = c.getGraphics();

        g.drawImage(render, 1, 1, c.getHeight(), c.getWidth(), c);

        return corte;
    }

    public void Treino_Reconhecimento(String root) {

        String trainingDir = root;// diretorio com as imagens devidamente tratadas e dimensionadas no mesmo tamanho

        System.out.print("criando diretorio de treino");
        File trainDir = new File(trainingDir); //Mahomeno um parse de string pra file

        FilenameFilter imgFilter;
        imgFilter = new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                name = name.toLowerCase();
                return name.endsWith(".jpg") || name.endsWith(".pgm") || name.endsWith(".png");// faz tratamento pra retornar soh imagens.
            }
        };

        File[] imageFiles = trainDir.listFiles(imgFilter);// retorna lista s das imagens

        MatVector images = new MatVector(imageFiles.length);// cria matriz de imagens com tamanho especfico
        System.out.print("criando vetor label");
        org.bytedeco.javacpp.opencv_core.Mat labels = new org.bytedeco.javacpp.opencv_core.Mat(imageFiles.length, 1,
                CV_32SC1);// matriz com as etiquetas das imagens, note que o valor de retorno na identificao  a etiqueta da imagem correspondente
        IntBuffer labelsBuf = labels.getIntBuffer();

        int counter = 0;

        for (File image : imageFiles) {
            org.bytedeco.javacpp.opencv_core.Mat img = imread(image.getAbsolutePath(), CV_LOAD_IMAGE_GRAYSCALE);// l imagem por imagem em escala de cinza
            System.out.print("Pegando label");
            int label = Integer.parseInt(image.getName().split("\\.")[0]);//etiqueta com equivalente numerico  do nome da imagem, sim,  genial.

            images.put(counter, img);//seta a imagem com o numero

            labelsBuf.put(counter, label);//seta a etiqueta com o numero

            counter++;
        }

        FaceRecognizer faceRecognizer = createLBPHFaceRecognizer();

        faceRecognizer.train(images, labels);//D xp ao bichinho
        faceRecognizer.set("threshold", 100);

        SettingsDAO settings = new SettingsDAO();
        faceRecognizer.save(settings.getSettings().getRecogXMLPath() + "\\faceID.xml");
    }

    public FaceRecognizer load() {
        SettingsDAO settings = new SettingsDAO();

        FaceRecognizer fr = createLBPHFaceRecognizer();
        fr.load(settings.getSettings().getRecogXMLPath() + "\\faceID.xml");
        return fr;
    }

    public int Predict(Mat rosto) {
        SettingsDAO s = new SettingsDAO();
        String caminho = s.getSettings().getRecogImageSetPath() + "\\comp\\testcomp.jpg";
        Highgui.imwrite(caminho, rosto);

        try {
            Thread.sleep(300);
        } catch (InterruptedException ex) {
            Logger.getLogger(ImgProcess.class.getName()).log(Level.SEVERE, null, ex);
        }

        FaceRecognizer fr;
        fr = load();
        org.bytedeco.javacpp.opencv_core.Mat testImage = imread(caminho, CV_LOAD_IMAGE_GRAYSCALE);
        int predict = fr.predict(testImage);
        System.out.println("Predicted label: " + predict);
        return predict;

    }

}