Example usage for org.opencv.core Mat empty

List of usage examples for org.opencv.core Mat empty

Introduction

In this page you can find the example usage for org.opencv.core Mat empty.

Prototype

public boolean empty() 

Source Link

Usage

From source file:usefull.CaptureVideo.java

License:LGPL

public static void main(String[] args) throws InterruptedException {

    // load the Core OpenCV library by name

    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    // create video capture device object

    VideoCapture cap = new VideoCapture();

    // try to use the hardware device if present

    int CAM_TO_USE = 0;

    // create a new image object

    Mat matFrame = new Mat();

    // try to open first capture device (0)

    try {//from   w w w.ja va 2 s . c  o  m
        cap.open(CAM_TO_USE);
    } catch (Exception e1) {
        System.out.println("No webcam attached");

        // otherwise try opening a video file 

        try {
            cap.open("files/video.mp4");
        } catch (Exception e2) {
            System.out.println("No video file found");
        }
    }

    // if the a video capture source is now open

    if (cap.isOpened()) {

        // create a new window object

        Imshow ims = new Imshow("From video source ... ");

        boolean keepProcessing = true;

        while (keepProcessing) {
            // grab the next frame from video source

            cap.grab();

            // decode and return the grabbed video frame

            cap.retrieve(matFrame);

            // if the frame is valid (not end of video for example)

            if (!(matFrame.empty())) {
                // *** to any processing here*** 

                // display image with a delay of 40ms (i.e. 1000 ms / 25 = 25 fps)

                ims.showImage(matFrame);
                Thread.sleep(40);
            } else {
                keepProcessing = false;
            }
        }

    } else {
        System.out.println("error cannot open any capture source - exiting");
    }

    // close down the camera correctly

    cap.release();

}

From source file:usefull.hogPeopleDetection.java

License:LGPL

public static void main(String[] args) throws InterruptedException {

    // load the Core OpenCV library by name

    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    // create video capture device object

    VideoCapture cap = new VideoCapture();

    // try to use the hardware device if present

    int CAM_TO_USE = 0;

    // create a new image object

    Mat matFrame = new Mat();

    // try to open first capture device (0)

    try {/*  ww w . j a va  2s  .c  o  m*/
        cap.open(CAM_TO_USE);
    } catch (Exception e1) {
        System.out.println("No webcam attached");

        // otherwise try opening a video file 

        try {
            cap.open("files/video.mp4");
        } catch (Exception e2) {
            System.out.println("No video file found");
        }
    }

    // if the a video capture source is now open

    if (cap.isOpened()) {

        // create a new window object

        Imshow ims = new Imshow("HOG People Detection");

        boolean keepProcessing = true;

        // create new HoG detection object

        HOGDescriptor HOG = new HOGDescriptor();
        HOG.setSVMDetector(HOGDescriptor.getDefaultPeopleDetector());

        // create 

        MatOfRect foundLocations = new MatOfRect();
        MatOfDouble foundWeights = new MatOfDouble();

        while (keepProcessing) {
            // grab the next frame from video source

            cap.grab();

            // decode and return the grabbed video frame

            cap.retrieve(matFrame);

            // if the frame is valid (not end of video for example)

            if (!(matFrame.empty())) {
                // perform detection

                HOG.detectMultiScale(matFrame, foundLocations, foundWeights, 0, new Size(8, 8),
                        new Size(32, 32), 1.05, 8, false);

                List<Rect> rectangles = foundLocations.toList();

                for (int i = 0; i < rectangles.size(); i++) {

                    Core.rectangle(matFrame, new Point(rectangles.get(i).x, rectangles.get(i).y),
                            new Point(rectangles.get(i).x + rectangles.get(i).width,
                                    rectangles.get(i).y + rectangles.get(i).height),
                            new Scalar(255, 0, 0), 2, 1, 0);
                }

                // display image with a delay of 40ms (i.e. 1000 ms / 25 = 25 fps)

                ims.showImage(matFrame);
                Thread.sleep(40);
            } else {
                keepProcessing = false;
            }
        }

    } else {
        System.out.println("error cannot open any capture source - exiting");
    }

    // close down the camera correctly

    cap.release();

}

From source file:view.TelaComCaptura.java

public void mostraVideo(JPanel containerVideo, Thread t) {

    Utils ut = new Utils();
    Graphics g = containerVideo.getGraphics();
    //Matriz que contem os dados da imagem
    Mat frame = new Mat();
    Mat frameSemRetangulo = new Mat();

    if (captura != null) {
        if (captura.isOpened()) {
            captura.release();//from   w w w  . ja va 2  s. c  o  m
        }
    }

    try {
        captura = new VideoCapture(0);
    } catch (Exception e) {
        Utils.msgErro("Erro ao iniciar webcam", "Erro");
    }

    ClassificadorFacial.classificador = new CascadeClassifier(
            "resources\\cascades\\haarcascade_frontalface_alt.xml");
    // String cascadeFile = localPath + "\\resources\\cascades\\haarcascade_frontalface_alt.xml";
    //String cascadePath = cascadeFile;
    //CascadeClassifier classificador = new CascadeClassifier();
    //classificador.load(cascadeFile);

    //        if (!classificador.load(cascadeFile)) {
    //            System.out.println("Erro ao carregar cascade file");
    //
    //            if (!new File(cascadeFile).canRead()) {
    //                new File(cascadeFile).setReadable(true);
    //                System.out.println("Arquivo travado");
    //            }
    //
    //            return;
    //        } else {
    //            if (new File(cascadeFile).canRead()) {
    //                System.out.println("Arquivo liberado");
    //            }
    //        }
    MatOfRect facesDetectadas = new MatOfRect();
    double scaleFactor = 1.1;
    int minNeighbors = 2;
    int flags = 0;
    Size minSize = new Size(30, 30);
    Size maxSize = new Size(500, 500);
    Scalar cor = new Scalar(0, 255, 0);
    int larguraPanel = containerVideo.getWidth();
    int alturaPanel = containerVideo.getHeight();
    int thickness = 3;

    while (!t.isInterrupted()) {

        //            try {
        //                Thread.sleep(100);
        //            } catch (InterruptedException ex) {
        //                Logger.getLogger(TelaComCaptura.class.getName()).log(Level.SEVERE, null, ex);
        //            }
        if (captura.isOpened()) {
            //Captura um frame
            captura.read(frame);
            if (!frame.empty()) {
                // setSize(frame.width(), frame.height());
                Mat imagemColorida = frame;
                Mat imagemCinza = new Mat();
                Imgproc.cvtColor(imagemColorida, imagemCinza, Imgproc.COLOR_BGR2GRAY);

                //Detecta faces
                ClassificadorFacial.classificador.detectMultiScale(imagemCinza, facesDetectadas, scaleFactor,
                        minNeighbors, flags, minSize, maxSize);
                Rect[] faces = facesDetectadas.toArray();
                frame.copyTo(frameSemRetangulo);
                Rect faceRecortada = null;

                if (lstFacesRecortadas.size() > faces.length) {
                    lstFacesRecortadas.clear();
                }

                for (int i = 0; i < faces.length; i++) {
                    Imgproc.rectangle(frame, faces[i].tl(), faces[i].br(), cor, thickness);

                    int larguraFace = (int) (faces[i].width * 0.8f);
                    int alturaFace = (int) (faces[i].height * 0.8f);

                    faceRecortada = new Rect(faces[i].x + 20, faces[i].y + 20, larguraFace, alturaFace);
                    // faceRecortada = new Rect(faces[i].x, faces[i].y, 150, 160);
                    if (faceRecortada != null) {
                        // if (lstFacesRecortadas.size() < faces.length) {
                        //System.out.println("Pessoa entrou da captura");

                        try {
                            //lstFacesRecortadas.add(ut.matToBufferedImage(new Mat(frameSemRetangulo, faceRecortada)));
                            lstFacesRecortadas.add(new Mat(frameSemRetangulo, faceRecortada));
                        } catch (Exception e) {
                        }

                        //                            } else if (lstFacesRecortadas.size() > faces.length) {
                        //                                //System.out.println("Pessoa saiu da captura");
                        //                                lstFacesRecortadas.clear();
                        //                                lstFacesRecortadas.add(ut.matToBufferedImage(new Mat(frameSemRetangulo, faceRecortada)));
                        //                            }
                    }

                }

                BufferedImage frameLimpo = ut.matToBufferedImage(frameSemRetangulo);
                BufferedImage frameComRetangulos = ut.matToBufferedImage(frame);

                this.setFrameAtual(frameLimpo);

                g.drawImage(frameComRetangulos, 0, 0, larguraPanel, alturaPanel, null);

                //Limpa variveis
                imagemCinza = null;
                faceRecortada = null;
                frameLimpo = null;
                if (!isSalvandoPGM()) {
                    //lstFacesRecortadas.clear();
                }

                frameComRetangulos = null;

            }
        }
    }

    captura.release();
    //new File(cascadeFile).
    System.out.println("Captura finalizada");
}

From source file:webcamfacedetect.WebcamFaceDetect.java

/**
 * @param args the command line arguments
 *///from w  w w.j  av  a2s .  c  o m
public static void main(String args[]) {
    // Load the native library.
    Libloader.load();
    String window_name = "Capture - Face detection";
    JFrame frame = new JFrame(window_name);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1024, 800);
    FaceDetect faceDetect = new FaceDetect();
    Processor my_processor = new Processor();
    frame.setContentPane(faceDetect);
    frame.setVisible(true);
    // Read the video stream  
    Mat webcam_image = new Mat();
    VideoCapture capture = null;
    for (int numCam = 0; numCam < 5; numCam++) {
        try {
            capture = new VideoCapture(numCam);
            break;
        } catch (Exception e) {
            System.out.println("Webcam number " + numCam + " unavailable ...");
        }
    }
    if (capture.isOpened()) {
        while (true) {
            capture.read(webcam_image);
            if (!webcam_image.empty()) {
                frame.setSize(webcam_image.width() + 40, webcam_image.height() + 60);
                // Apply the classifier to the captured image  
                webcam_image = my_processor.detect(webcam_image);
                // Display recognized image  
                faceDetect.MatToBufferedImage(webcam_image);
                faceDetect.repaint();
            } else {
                System.out.println("No captured frame. Exit.");
                break;
            }
        }
    }
}