Example usage for org.opencv.videoio VideoCapture VideoCapture

List of usage examples for org.opencv.videoio VideoCapture VideoCapture

Introduction

In this page you can find the example usage for org.opencv.videoio VideoCapture VideoCapture.

Prototype

public VideoCapture(int index) 

Source Link

Usage

From source file:readnumber.ReadNumber.java

/**
 * //from  w w w.j a va 2 s. c  om
 * @param args runMainLoop - VideoCapture
 */

private void runMainLoop(String[] args) {
    imageProcessor = new ImageProcessor();
    webcamMatImage = new Mat();
    Image tempImage;
    VideoCapture capture = new VideoCapture(0);
    capture.set(Videoio.CAP_PROP_FRAME_WIDTH, 320);
    capture.set(Videoio.CAP_PROP_FRAME_HEIGHT, 240);

    // Create a face detector from the cascade file                
    faceDetector = new CascadeClassifier(CascadeFile);

    if (capture.isOpened()) {
        while (true) {
            capture.read(webcamMatImage);
            if (!webcamMatImage.empty()) {
                // Output video to form (JLabel)
                //imageLabel.setBounds(0, 61, 320, 240);
                tempImage = imageProcessor.toBufferedImage(webcamMatImage);
                ImageIcon imageIcon = new ImageIcon(tempImage, "Captured video");
                imageLabel.setIcon(imageIcon);
                Buttonl.setBounds(10, 0, 140, 30);
                //Button2.setBounds(140, 0, 120, 30);
                message.setBounds(10, 30, 200, 30);
                inform.setBounds(10, 315, 200, 30);
                caunttext.setBounds(100, 315, 200, 30);
                textVideo.setBounds(10, 295, 120, 30);

                //frame.pack();  //this will resize the window to fit the image
            } else {
                System.out.println(" -- Frame not captured -- Break!");
                break;
            }
        }
    } else {
        System.out.println("Couldn't open capture.");
    }

}

From source file:russ.camera.VideoStream.java

public VideoStream() {

    System.out.println("Hello, OpenCV");
    // Load the native library.
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    camera = new VideoCapture(0);
    camera.set(CAP_PROP_FPS, 30);/*from  w  w w .  ja  v  a 2  s .  co  m*/
    try {
        Thread.sleep(10);
    } catch (InterruptedException ex) {

    }
    if (!camera.isOpened()) {
        System.out.println("Camera Error");
    } else {
        System.out.println("Camera OK?");
    }

    imageMatrix = new Mat();

    //camera.set(CAP_PROP_FRAME_WIDTH, 640);
    //camera.set(CAP_PROP_FRAME_HEIGHT, 480);
}

From source file:servershootingstar.BallDetector.java

public static String getAngleFromRobot(int input) {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    System.out.println("before");
    int point;/*w  w w. j a  v  a  2  s . co  m*/
    try {
        Mat frame = new Mat();
        System.out.println("AAAAAA");
        Mat originalFrame = new Mat();
        System.out.println("BBBBBB");
        VideoCapture videoCapture = new VideoCapture(0);
        System.out.println("CCCCCCCC");
        videoCapture.read(originalFrame);
        //                System.out.println("original" + originalFrame.dump());
        //                initSwing(originalFrame);
        int workaround = 20;
        while (workaround > 0) {
            System.out.println("workaround " + workaround);
            videoCapture.read(originalFrame);
            //                    System.out.println(originalFrame.dump() + originalFrame.dump().length());
            workaround--;
        }
        //                Imgcodecs.imwrite("C:\\Users\\Goran\\Desktop\\Goran.jpg", originalFrame);
        Mat cropped = originalFrame.submat(originalFrame.rows() / 4, originalFrame.rows() / 4 * 3, 0,
                originalFrame.cols());
        initSwing(cropped);
        Imgproc.cvtColor(cropped, frame, Imgproc.COLOR_BGR2HSV);

        // insert lower and upper bounds for colors
        Scalar greenLowerB = new Scalar(20, 55, 55);
        Scalar greenUpperB = new Scalar(40, 255, 255);

        Scalar redLowerB = new Scalar(160, 100, 35);
        Scalar red1LowerB = new Scalar(0, 100, 35);

        Scalar redUpperB = new Scalar(180, 255, 255);
        Scalar red1UpperB = new Scalar(20, 255, 255);

        Scalar blueLowerB = new Scalar(100, 100, 35);
        Scalar blueUpperB = new Scalar(120, 255, 155);

        Mat mask = new Mat();

        if (input == 1) {
            Mat otherMask = new Mat();
            Core.inRange(frame, redLowerB, redUpperB, mask);
            Core.inRange(frame, red1LowerB, red1UpperB, otherMask);
            Core.bitwise_or(mask, otherMask, mask);
        } else if (input == 2) {
            Core.inRange(frame, greenLowerB, greenUpperB, mask);
        } else {
            Core.inRange(frame, blueLowerB, blueUpperB, mask);
        }
        Imgproc.erode(mask, mask, Imgproc.getStructuringElement(Imgproc.CV_SHAPE_ELLIPSE, new Size(5, 5)));
        Imgproc.erode(mask, mask, Imgproc.getStructuringElement(Imgproc.CV_SHAPE_ELLIPSE, new Size(5, 5)));
        Imgproc.erode(mask, mask, Imgproc.getStructuringElement(Imgproc.CV_SHAPE_ELLIPSE, new Size(5, 5)));
        Imgproc.erode(mask, mask, Imgproc.getStructuringElement(Imgproc.CV_SHAPE_ELLIPSE, new Size(5, 5)));

        int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE, minY = Integer.MAX_VALUE,
                maxY = Integer.MIN_VALUE;
        for (int i = 0; i < mask.rows(); ++i) {
            for (int j = 0; j < mask.cols(); ++j) {
                double value = mask.get(i, j)[0];
                //System.out.println(value);
                if (value > 1) {
                    minX = Math.min(minX, i);
                    maxX = Math.max(maxX, i);
                    minY = Math.min(minY, j);
                    maxY = Math.max(maxY, j);
                }
            }
        }

        Imgproc.circle(mask, new Point((maxY + minY) / 2, (minX + maxX) / 2), 3, new Scalar(0, 0, 0));
        initSwing(mask);

        point = (minY + maxY) / 2;

        point = point - 320;

        cos = point / 320.0;
        System.out.println("OK");
    } catch (Exception ex) {
        point = (new Random()).nextInt(640);
        cos = -1;
        System.out.println("error imase, davam random brojka: " + point);
        ex.printStackTrace();

    }

    //            System.out.println();
    //            System.out.println("tockata u granica od [-320, 320]");
    //            System.out.println(point);
    //            System.out.println("cosinus vrednost");
    //            System.out.println(cos);
    //            System.out.println();
    System.out.println("cos = " + cos);
    if (cos == -1) {
        return "-1";
    }
    int res = (int) (2 * Math.toDegrees(Math.acos(cos)) / 3);
    System.out.println("Res: " + res);
    return String.valueOf(res);
}

From source file:spycam.Spycam.java

public static void main(String args[]) {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    VideoCapture camera = new VideoCapture(0);

    if (!camera.isOpened()) {
        System.out.println("Error");
    } else {/*from   w w  w .  j  a  v  a2s .  c  o  m*/
        Mat frame = new Mat();
        while (true) {
            if (camera.read(frame)) {
                System.out.println("Frame Obtained");
                System.out.println("Captured Frame Width " + frame.width() + " Height " + frame.height());
                Imgcodecs.imwrite("camera.jpg", frame);
                System.out.println("OK");
                break;
            }
        }
    }
    camera.release();
}

From source file:Telas.TelaCadastroUsuario.java

private void configuraComponentes() {
    btnSalvar.setIcon(UtilInterface.ICONE_SALVAR);
    btnCancelar.setIcon(UtilInterface.ICONE_CANCELAR);
    UtilInterface.setFontes(pnTudo.getComponents());
    UtilInterface.setFontes(jPanel2.getComponents());
    webSource = new VideoCapture(0);
    if (webSource.grab()) {
        btnCam.setEnabled(true);/* w  w  w.  j av  a 2s  .c om*/
    }

    txConfirmSenha.setDocument(new LimitaCaracteres(50));
    txEmail.setDocument(new LimitaCaracteres(50));
    txNome.setDocument(new LimitaCaracteres(50));
    txNomeUser.setDocument(new LimitaCaracteres(50));
    txSenha.setDocument(new LimitaCaracteres(50));
}

From source file:test_2.MainFrame.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    vedio = new VideoCapture(0);
    mat = new Mat();
    MB = new MatOfByte();
    jButton5.setEnabled(true);//w ww.j  a v  a2 s.  co  m
    jButton4.setEnabled(false);
    jButton1.setEnabled(false);
    jButton2.setEnabled(false);
    jButton3.setEnabled(false);
    Mat mat2 = new Mat();
    Mat mat1 = new Mat();
    wid = 1;
    hghi = 1;
    boolean f = false;
    t = new Thread() {
        public void run() {
            while (true) {
                try {
                    vedio.grab();
                    vedio.retrieve(mat1);
                    vedio.retrieve(mat2);
                    mat = CoreCode.points(mat1, mat2, chose, jPanel1.getWidth(), jPanel1.getHeight());
                    Core.flip(mat, mat, 2);
                    Imgcodecs.imencode(".jpg", mat, MB);
                    Image img = ImageIO.read(new ByteArrayInputStream(MB.toArray()));
                    BufferedImage buf = (BufferedImage) img;
                    Graphics2D g = (Graphics2D) jPanel1.getGraphics();
                    g.scale(wid, hghi);
                    g.drawImage(img, 0, 0, jPanel1.getWidth(), jPanel1.getHeight(), 0, 0, buf.getWidth(),
                            buf.getHeight(), null);
                    if (CoreCode.isCcircel()) {
                        wid = 1.6;
                        hghi = 1.6;
                        ch = true;
                        CoreCode.left = false;
                        CoreCode.right = false;
                        CoreCode.booton = false;
                    }
                    if (CoreCode.isleft()) {

                        jLabel1.setText("left");
                        System.exit(0);

                    }

                    else if (CoreCode.isRight()) {
                        jLabel1.setText("snaping shoot " + it);
                        Imgcodecs.imwrite("shoot number " + it + ".jpg", mat);
                        it++;
                        CoreCode.setRight(false);
                        ch = false;
                    } else if (CoreCode.isUp()) {
                        CoreCode.up = false;
                        if (ch) {
                            wid = 1;
                            hghi = 1;
                            ch = false;
                            CoreCode.setCcircel(false);
                        } else {
                            jLabel1.setText("Up");
                            chose = 2;
                        }
                    } else if (CoreCode.isBooton()) {
                        jLabel1.setText("down");
                        chose = 1;
                    }
                } catch (Exception ex) {
                    System.out.println("Error zoraar Vedio");
                }
            }
        }
    };
    t.start();
}

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  va2  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
 *///  w w  w .j a  va  2  s . co 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;
            }
        }
    }
}