opencv.CamCapture.java Source code

Java tutorial

Introduction

Here is the source code for opencv.CamCapture.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 opencv;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.videoio.VideoCapture;

/**
 *
 * @author Aryandev
 */
public class CamCapture extends javax.swing.JFrame {

    /**
     * Creates new form CamCapture
     */
    int stopflag;
    private VideoCapture vc;
    private Thread t;

    public CamCapture() {
        stopflag = 0;
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();

        jLabel1.setText("jLabel1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Start");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText("It's Drjslab Creation");

        jLabel3.setBackground(new java.awt.Color(0, 0, 0));
        jLabel3.setText("Cam Capture");
        jLabel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jButton2.setText("Stop & Exit");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel4.setText("Operation ");
        jLabel4.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel5.setText("Detacted motion");
        jLabel5.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 84,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(54, 54, 54).addComponent(jButton2,
                                                javax.swing.GroupLayout.PREFERRED_SIZE, 117,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 300,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 300,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 300,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(21, 21, 21)));
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup().addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 300,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 300,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup().addGap(16, 16, 16).addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(jButton1).addComponent(jButton2))
                                                .addPreferredGap(
                                                        javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(jLabel2))
                                        .addGroup(layout.createSequentialGroup().addGap(18, 18, 18).addComponent(
                                                jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 300,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addContainerGap(30, Short.MAX_VALUE)));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        stopflag = 1;
        System.loadLibrary("opencv_java300");
        vc = new VideoCapture(0);
        final int SENSITIVITY_VALUE = 20;
        final int BLUR_SIZE = 10;
        final int WIDTH = jLabel3.getHeight();
        final int HEIGHT = jLabel3.getWidth();
        try {
            t = new Thread() {

                Mat previousFrame = new Mat();
                Mat currentFrame = new Mat();
                Mat grayImage1 = new Mat();
                Mat grayImage2 = new Mat();
                Mat differenceImage = new Mat();
                Mat thresholdImage = new Mat();

                @Override
                public void run() {

                    while (true) {
                        if (vc.isOpened()) {

                            vc.read(previousFrame);
                            Imgproc.resize(previousFrame, previousFrame, new Size(HEIGHT, WIDTH));
                            Imgproc.cvtColor(previousFrame, grayImage1, Imgproc.COLOR_BGR2GRAY);

                            vc.read(currentFrame);
                            Imgproc.resize(currentFrame, currentFrame, new Size(HEIGHT, WIDTH));
                            Imgproc.cvtColor(currentFrame, grayImage2, Imgproc.COLOR_BGR2GRAY);

                            //movement Search

                            Core.absdiff(grayImage1, grayImage2, differenceImage);
                            Imgproc.threshold(differenceImage, thresholdImage, SENSITIVITY_VALUE, 255,
                                    Imgproc.THRESH_BINARY);
                            Imgproc.blur(thresholdImage, thresholdImage, new Size(BLUR_SIZE, BLUR_SIZE));
                            Imgproc.threshold(thresholdImage, thresholdImage, SENSITIVITY_VALUE, 255,
                                    Imgproc.THRESH_BINARY);
                            jLabel4.setIcon(new ImageIcon(Mat2bufferedImage(thresholdImage)));
                            searchForMovement(thresholdImage, currentFrame);
                            //Previous frame is now this frame
                            grayImage2.copyTo(grayImage1);
                            ImageIcon i = new ImageIcon(Mat2bufferedImage(previousFrame));
                            jLabel3.setIcon(i);
                            jLabel3.repaint();

                            if (stopflag == 0) {
                                vc.release();
                                break;
                            }
                        } else {

                            System.err.println("Cam Error");
                        }
                    }

                };

            };
        } catch (Exception e) {
            System.err.println(e.toString());
        }
        t.start();

    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:

        stopflag = 0;
        vc.release();
        System.exit(0);
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CamCapture.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CamCapture.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CamCapture.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CamCapture.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CamCapture().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    // End of variables declaration//GEN-END:variables

    private BufferedImage Mat2bufferedImage(Mat m) {
        MatOfByte bytemat = new MatOfByte();
        Imgcodecs.imencode(".jpg", m, bytemat);
        byte[] bytes = bytemat.toArray();
        InputStream in = new ByteArrayInputStream(bytes);
        BufferedImage img = null;
        try {
            img = ImageIO.read(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return img;
    }

    private void searchForMovement(Mat thresholdImage, Mat frame) {
        List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
        Mat hierarchy = new Mat();
        Imgproc.findContours(thresholdImage, contours, hierarchy, Imgproc.RETR_EXTERNAL,
                Imgproc.CHAIN_APPROX_SIMPLE);

        Rect objectBoundingRectangle = new Rect(0, 0, 0, 0);
        for (int i = 0; i < contours.size(); i++) {
            objectBoundingRectangle = Imgproc.boundingRect(contours.get(i));
            if (objectBoundingRectangle.area() > 500)
                Imgproc.rectangle(frame, objectBoundingRectangle.tl(), objectBoundingRectangle.br(),
                        new Scalar(0, 255, 0));
        }
        ImageIcon i2 = new ImageIcon(Mat2bufferedImage(frame));
        jLabel5.setIcon(i2);

    }

}